Skip to content

Instantly share code, notes, and snippets.

@tasaquino
Last active March 7, 2018 14:08
Show Gist options
  • Save tasaquino/9ce0b16a049b9e3f6a6992e6e95e75bf to your computer and use it in GitHub Desktop.
Save tasaquino/9ce0b16a049b9e3f6a6992e6e95e75bf to your computer and use it in GitHub Desktop.
Kotlin - when with smart cast example
interface House
class Stark : House{
fun wolves() = arrayListOf("Ghost", "Grey Wind", "Summer", "Lady", "ShaggyDog", "Nymeria")
}
class Targeryen : House{
fun daenerysDragons() = arrayListOf("Drogon", "Viserion", "Rhaegal")
}
fun printAnimalsOf(house: House) =
when (house) {
is Stark -> house.wolves()
is Targeryen -> house.daenerysDragons()
else -> throw IllegalArgumentException("Unknown house")
}
fun main(args: Array<String>) {
println(printAnimalsOf(Targeryen()))
// [Drogon, Viserion, Rhaegal]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment