June 2018
Intermediate to advanced
310 pages
6h 32m
English
Coming from Java, you may be inclined to check what type your object is using, is, and cast it using as:
interface Superheroclass 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) { ...Read now
Unlock full access