開発環境
- 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 11(lambdas and higher-order functions - Treating Code Like Data)、Pool Puzzle(346)の解答を求めてみる。
コード
fun unless(condition: Boolean, code: () -> Unit) { if (!condition) { code() } } fun main() { val options = arrayOf("Red", "Amber", "Green") for (n in 1..10) { print("n = $n: ") var crossWalk = options[kotlin.random.Random.nextInt(options.size)] if (crossWalk == "Green") { println("Walk!") } unless(crossWalk == "Green") { println("Stop!") } } }
入出力結果
n = 1: Stop! n = 2: Stop! n = 3: Stop! n = 4: Stop! n = 5: Walk! n = 6: Stop! n = 7: Walk! n = 8: Stop! n = 9: Stop! n = 10: Stop! Process finished with exit code 0
0 コメント:
コメントを投稿