Left Index

Kotlin Smart Cast

To use this nullable types we have an option to use smart casts. Smart cast is a feature in which Kotlin compiler tracks conditions inside if expression. If compiler founds a variable is not null of type nullable then the compiler will allow to access the variable.

Example:
package com.theitbulls.kotlinex

fun main(args: Array<String>) {
	var name: String? = "John"

	// compiler error 
	// i.e. Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type String?
	println(name.toUpperCase()) 

	// or

	// compiler error 
	// i.e. Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type String?
	println(name.length)
}

To solve the above expression we use a safe cast as:

Example:
package com.theitbulls.kotlinex

fun main(args: Array<String>) {
	var name: String? = "John"

	if(name != null) {
		// now it will work
		println(name.toUpperCase())
	}
	
	// or 
	name?.let { println(it.toUpperCase()) } 
}
Output:
JOHN
JOHN

Use of 'is' for smart cast: While using is or !is for checking the variable, the compiler tracks this information and internally cast the variable to target type. This is done inside the scope if is or !is returns true.

Example:
package com.theitbulls.kotlinex

fun main(args: Array<String>) {
	var name: String? = "Hello The It Bulls totorial"

	if (name is String) {
		// No Explicit Casting needed.  
		println(name.length)
	}
}
Output:
27

Using when expression: We can easily replace the if-else blocks with when expression. We have already learnt about when expression in control flow articles. For more details, we can refer when expression in Kotlin

Example:
package com.theitbulls.kotlinex

fun main(args: Array<String>) {
	var empData = listOf("John Carlo", 34, 49.40f)
	
	for(emp in empData) {
		when(emp) {
			// smart casting 
			is String -> println("Employee name: ${emp}")
			is Int -> println("Employee age: ${emp}")
			is Float -> println("Employee salary: ${emp}")
		}
	}
}
Output:
Employee name: John Carlo
Employee age: 34
Employee salary: 49.4