Smart Casts

This Atom is Under Construction

A smart cast reduces the amount of work required when working with different types.

If you check whether a value is a particular type (using the is keyword), any code within the scope of that check assumes that it is that type:

if (alice is Human) { // Code in this block assumes // alice is a Human object }

In the following, barkIfDog() can just call bark() on a if a is of type Dog. Other programming languages require an additional, explicit cast of a to Dog, even though you just checked to see if it was a Dog:

// SmartCasts/SmartCasts.kt package smartcasts import atomictest.eq class Dog { fun bark() = "yip!" } fun barkIfDog(a: Any) = if (a is Dog) a.bark() else "not Dog" fun main(args: Array<String>) { barkIfDog(Dog()) eq "yip!" barkIfDog(42) eq "not Dog" }

End of sample. See AtomicKotlin.com for full early-access book.



Previous          Next

©2018 Mindview LLC. All Rights Reserved.