You are here
Home > Kotlin

Kotlin:Smart Casts and Function Return

Smart Casts

Smart Casts and Function Return

In this post we will discuss kotlin Smart Casts and function return value, Type hierarchy with example.

Smart Casts

  • In kotlin we check the type of instance using the is
  • Kotlin compiler is more intelligent, then java compiler.
  • Kotlin compiler remember type checks for us, implicitly cast the reference to the more specific type.

Example:
fun test(x: Any)
{
if (x is String){
println(x) // x is automatically cast to String
}
if (x is Int) {
println(x+1) // x is automatically cast to Integer
}
}
// The above can be rewritten with when statement
fun check(x: Any) = when(x) {
is String -> println(x)
is Int -> println(x+1)
else -> println(“Error”)
}
fun main(args:Array<String>)
{
test(“Hello”) // Hello
test(6) // 7
check(“Kotlin”) // Kotlin
check(2.0) // Error
}
output:

Explanation:
Here we create function test() with parameter x of type Any and in if statement we check x is string and kotlin automatically convert Any to String. We create other function check() with parameter x here we use when expression.

Type Hierarchy

  • Same as all other languages kotlin also has uppermost type called In kotlin all class by default extends the Any superclass. It has three methods tostring(), equals(), hashcode().
  • In java if function not return any value we use void type and in kotlin we use Unit The difference between them is void is not any data type, but it is case that is used to indicate complier function not return any value. where Unit is a data type, with singleton instance. It is also referred to Unit or ().

Function Return

  • If we use function and you have to return a value use return
  • Ex:

Fun mul(x:Int,y:Int):Int
{
return(x*y);
}

  • By default, return returns the nearest function. In nested function, it will return inner most function.

Example:
fun mul(x:Int,y:Int):Int
{
return(x*y)
}
fun minimum(x:Int,y:Int,z:Int):Int
{
fun min(x:Int,y:Int):Int
{
if(x<y) return x;
else return y;
}
return min(min(x,y),z)
}
fun main(args:Array<String>)
{
println(“multiplication of 2 and 5=”+mul(2,5));
println(“minimum of 4,6,8=”+minimum(4,6,8));
}
output:

Keep Visiting TechwithR.com for more upcoming top technical articles and also see my new blog Mag4info. and for kotlin tutorial also see my blog kotlin category.
You can also by SQL 70-761 book write by me from Amazon.
You can also by Kotlin Book write by me from Amazon.

Leave a Reply

Top