Challenges 2 and 3: I altered the castFireballs function. Again I had to add “else” or an error message appeared.
private fun castFireball(numFireballs: Int = 2, inebStatus: Int = 10) =
if (numFireballs > 0) {
println(“A glass of Fireball springs into existence (x$numFireballs).”)
when (inebStatus) {
in 1…10 -> “tipsy”
in 11…20 -> “sloshed”
in 21…30 -> “soused”
in 31…40 -> “stewed”
in 41…50 -> “…t0aSt3d”
else -> “The fireball has no effect.”
}
} else {
println(“No fireballs today!”)
}
Then I changed the printPlayerStatus function adding one line.
private fun printPlayerStatus(
… println(“Inebriation Status: ${castFireball(2, 5)}”)
}
it seems that there has to be always an ‘else’ branch inside of the ‘when’ expression to make it exhaustive (the compiler said)
It is a nice solution.
I thought a bit to much outside the box.
This is my solution:
fun main(args: Array<String>) {
// Cast Fireball
val inebriationLevel = castFireball()
// Print Inebriation Status description for inebriationLevel
val inebriationStatus = inebriationLevelStatus(inebriationLevel)
}
private fun castFireball(numFireballs: Int = 2) : Int {
println("A glass of Fireball springs into existence. (x$numFireballs)")
// Get Fireball Inebriation Level
var minInebriation : Int
if (numFireballs < 50) minInebriation = numFireballs else minInebriation = 50
val fireballInebriation = (minInebriation..50).random()
return fireballInebriation
}
private fun inebriationLevelStatus(inebriationLevel: Int) {
val inebriationStatus = when (inebriationLevel) {
in 41..50 -> "..t0aSt3d"
in 31..40 -> "stewed"
in 21..30 -> "soused"
in 11..20 -> "sloshed"
in 1..10 -> "tipsy"
else -> "none"
}
println("Inebriation: $inebriationStatus ($inebriationLevel)")
}