Josh Skeen, David Greenhalgh著『Kotlinプログラミング』には章末問題がある。残念なことに解答がないので、第3章に引き続き本を読み進めながら答案を記述する。
もし回答に間違いや意見があれば、ぜひご指摘いただきたい。
第4章 章末問題 回答案
4.15 チャレンジ! 単一式
関数auraColor()を単一式関数の構文を使って書き直せるかという命題であるが、単一式関数の構文は、本書p60で対象になる関数が評価すべき式をただ1つだけ持つときに利用できると書かれている。それではauraColor()関数を見て、この条件に当てはまるかみよう。
private fun auraColor(isBlessed: Boolean, healthPoints: Int, isImmortal: Boolean): String {
val auraVisible = isBlessed && healthPoints > 50 || isImmortal
val auraColor = if (auraVisible) "GREEN" else "NONE"
return auraColor
}
auraColor()関数は、auraVisibleとauraColorと2つの式を持っている。よって単一式の構文は使えない。
4.16 チャレンジ! ファイヤーボールの酩酊レベル
第4.16項だけでは、課題の意味ががうまく汲み取れなかったので、第4.17項も併せて回答する。
4.17 チャレンジ!酩酊状態
現在の酩酊レベルをcurrentInebriationとし、castFireball()関数の中でfireBallをゲットする度にnumFireballsをinebriation加算し戻り値として返していく。
受け取ったcurrentInebriationは、printInebriationStatus()関数に与え、酩酊状態を表示する。
fun main() {
val name = "Madrigal"
var healthPoints = 89
val isBlessed = true
val isImmortal = false
var currentInebriation = 0
// Aura
val auraColor = auraColor(isBlessed, healthPoints, isImmortal)
val healthStatus = formatHealthStatus(healthPoints, isBlessed)
// Player status
printPlayerStatus(auraColor, isBlessed, name, healthStatus)
currentInebriation = castFireball(numFireballs = 3, currentInebriation = currentInebriation)
println("酩酊度 = $currentInebriation ")
printInebriationStatus(currentInebriation)
}
private fun printPlayerStatus(auraColor: String, isBlessed: Boolean, name: String, healthStatus: String ) {
println(
"(Aura: $auraColor) " +
"(Blessed: ${if (isBlessed) "YES" else "NO"})"
)
println("$name$healthStatus")
}
private fun auraColor(isBlessed: Boolean, healthPoints: Int, isImmortal: Boolean): String {
val auraVisible = isBlessed && healthPoints > 50 || isImmortal
val auraColor = if (auraVisible) "GREEN" else "NONE"
return auraColor
}
private fun formatHealthStatus(healthPoints: Int, isBlessed: Boolean): String = // 単一式関数
when (healthPoints) {
100 -> "は、絶好調だぜ!"
in 90..99 -> "は、ちょっどかすり傷を負った."
in 75..89 -> if (isBlessed) {
"は、ちょっと負傷したが、すぐ治るぜ!"
} else {
"は、ちょっと負傷した。"
}
in 15..74 -> "は、かなりやられた。"
else -> "は、やばい!"
}
private fun castFireball(numFireballs: Int = 2, currentInebriation: Int): Int { // Unit関数
println("ファイアーボールウイスキーを $numFireballs 杯ゲット。")
var inebriation = currentInebriation + numFireballs
if(inebriation > 50 ) inebriation = 50
return inebriation
}
private fun printInebriationStatus(currentInebriation: Int) {
var status = when (currentInebriation) {
0 -> "まったく酔ってない"
in 1..10 -> "ほろ酔い"
in 11..20 -> "へべれけ"
in 21..30 -> "へろへろ"
in 31..40 -> "ぐでんぐでん"
else -> "(表記不能)"
}
println("酩酊状態: $status")
}
(2020/12/09現在)