Smart cast

Any is a parent or a superclass of all classes in Kotlin. If our class is not derived from any class, then it has Any as a super class. All data types including Integer, Float, Double, and so on are derived from an Any class. (We will learn more about this in Chapter 3, The Four Pillars of Object-Oriented Programming). The following declarations are valid in Kotlin:

var any : Any? = null
any = 1234 // integer
any = "Hello" // String
any = 123.456 // Double

To understand the importance of smart casting, let's create a function with one parameter of the nullable Any? type:

fun mySmartCast(any :Any?)
{
if(any is Int)
{
var i = any + 5
println("Value is Int $i")
}
else if(any is String)
{
var s = "Hello " + any
println("Value is String $s")
}
else if (any == null) {
println("Object is null")
}
}

fun main (args: Array<String>) {
mySmartCast(8)
mySmartCast("Kotlin")
}

In the first function call with the integer value, the mySmartCast(8) smart cast not only takes care of the null type but also recognizes which type of class object it contains. Type checking, null safety, and unwrapping the object is handled by using the is operator. In the first if statement, the is operator verifies the null value and performs type casting as well.

Any is a superclass in Kotlin's class hierarchy.

Kotlin automatically converts Any into an integer to perform a mathematical operation on it, and we do not need to call toInt() function for type casting. Here is a smart cast example with the when expression:

fun mySmartCast(any :Any?){

when(any) {
is String -> println("String: $any")
is Int -> println("Integer: $any")
is Double -> println("Double: $any")
else -> println("Alian...")
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.97.75