Last active
March 7, 2018 14:08
-
-
Save tasaquino/9ce0b16a049b9e3f6a6992e6e95e75bf to your computer and use it in GitHub Desktop.
Kotlin - when with smart cast example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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