開発環境
- 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 8(nulls and exceptions - Safe and Sound)、Pool Puzzle(237)の解答を求めてみる。
コード
class Duck(val height: Int? = null) { fun quack() { println("Quack! Quack!") } } class MyDucks(var myDucks: Array<Duck?>) { fun quack() { for (duck in myDucks) { duck?.let { it.quack() } } } fun totalDuckHeight(): Int { var h: Int = 0 for (duck in myDucks) { h += duck?.height ?: 0 } return h } } fun main() { val ducks = arrayOf( Duck(1), Duck(2), null, Duck(3), Duck(4), null, Duck(5), null ) val myDucks = MyDucks(ducks) myDucks.quack() println(myDucks.totalDuckHeight()) }
入出力結果
Quack! Quack! Quack! Quack! Quack! Quack! Quack! Quack! Quack! Quack! 15 Process finished with exit code 0
0 コメント:
コメントを投稿