Coming from Java, you may be inclined to check what type your object is using, is, and cast it using as:
interface Superhero
class Batman : Superhero {
fun callRobin() {
println("To the Bat-pole, Robin!")
}
}
class Superman : Superhero {
fun fly() {
println("Up, up and away!")
}
}
fun doCoolStuff(s : Superhero) {
if (s is Superman) {
(s as Superman).fly()
}
else if (s is Batman) {
(a as Batman).callRobin()
}
}
But as you may know, Kotlin has smart casts, so implicit casting, in this case, is not needed:
fun doCoolStuff(s : Superhero) {
if (s is Superman) {
s.fly()
}
else if (s is Batman) {
s.callRobin()
}
}
Moreover, in most cases, using when() while smart-casting produces cleaner code:
fun doCoolStuff(s : Superhero) {
when(s) {
is Superman -> s.fly()
is Batman -> s.callRobin()
else -> println("Unknown superhero")
}
}
As a rule of thumb, you should avoid using casts and rely on smart casts most of the time:
// Superhero is clearly not a string
val superheroAsString = (s as String)
But if you absolutely must, there's also a safe cast operator:
val superheroAsString = (s as? String)