Type checks and casts
In Kotlin, it’s common to check an object’s type using is
and cast it using as
. However, Kotlin’s smart casts simplify this process. Let’s consider an example with a superhero system:
interface Superhero
class Batman : Superhero {
fun callRobin() {
println("To the Bat-pole, Robin!")
}
}
class Superman : Superhero {
fun fly() {
println("Up, up and away!")
}
}
// Function invoking a superhero's power
fun doCoolStuff(s: Superhero) {
if (s is Superman) {
s.fly()
} else if (s is Batman) {
s.callRobin()
}
}
Kotlin’s smart casting eliminates the need for explicit casting. The above function can be further optimized using when
, producing cleaner code. However, it makes it necessary to handle the else
case as long as it is not a sealed interface:
fun doCoolStuff(s: Superhero) {
when(s) {
is Superman -> s.fly()
...