Type Checking and Type Casting

5 0 0
                                        

is - works like instanceof of java. It checks if that object is an instance of the class.

==============

fun main(){

     var x = "5"

     if(x is String){

          println("Converting: ${x.toInt()}")

     }

}

==============

Result:

Converting: 5


The is type checking is useful when combine with when expressions. This when functions as a switch but it is an upgraded version. When expression uses lambda.

===============

fun main(){

     typeChecking(5)

}

fun typeChecking(x: Number){

     when(x){

          is Int -> println("Integer: $x")

          is Double -> println("Double: $x")

          else -> println("None of the above choices!")

     }

}

===============

Result:

Integer: 5

Note: The else is equivalent to default of switch. Just like saying if none of the above condition is true, use this else instead. Also, the type checking "is" was useful when combine with "when expression".


as - This is an infix operator use to convert the type to another type. This works well if you include null safe check when type casting (as?).

=================

fun main(){

     typeCasting(5.0);

}

fun typeCasting(x: Number){

     val num = x as? Double;

     println("x: $num")

}

=================

Result:

x: 5.0

Note: If the argument you use when invoking typeCasting(5) method is just 5 and you did not include a decimal. The result will be x: null since 5 is an Int type and not a Double type. null was also allowed as a return value since you use a null safe operator (?) after the "as" operator.

Kotlin ProgrammingWhere stories live. Discover now