開発環境
- macOS Mojave - Apple (OS)
- Windows 10 Pro (OS)
- IntelliJ IDEA CE(Community Edition) (IDE(統合開発環境))
- Kotlin (プログラミング言語)
Head First Kotlin: A Brain-Friendly Guide (Dawn Griffiths(著)、David Griffiths(著)、O'Reilly Media)のChapter 6(abstract classes and interfaces - Serious Polymorphism)、BE the Compiler(187)の解答を求めてみる。
コード
interface Flyable { val x: String fun fly() = println("$x is flying") } class Bird : Flyable { override val x = "Bird" } class Plane : Flyable { override val x = "Plane" } class Superhero : Flyable { override val x = "Superhero" } fun main() { val f = arrayOf(Bird(), Plane(), Superhero()) var x = 0 while (x in 0..2) { when (f[x]) { is Bird -> { x++ f[x].fly() } is Plane, is Superhero -> f[x].fly() } x++ } x = 0 while (x in 0..2) { val y = when (f[x]) { is Bird -> false else -> true } if (y) { f[x].fly() } x++ } for (t in f) { if (t is Plane || t is Superhero) t.fly() } }
入出力結果
Plane is flying Superhero is flying Plane is flying Superhero is flying Plane is flying Superhero is flying Process finished with exit code 0
0 コメント:
コメントを投稿