Challenges, my solutions

Challenge 1: I had to add “else” here or there was an error message.

private fun auraColor(isBlessed: Boolean, healthPoints: Int, isImmortal: Boolean) =
when (isBlessed && healthPoints > 50 || isImmortal) {
true -> “GREEN”
else -> “NONE”
}

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)}”)
}

Hey,

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)")
}

Best Regards

1 Like

here’s mine:

private fun castFireball(numFireballs: Int = 2) {
    println("A glass of Fireball springs into existence. (x$numFireballs)")
    var inebriation = "Inebriation level: "
    if (numFireballs > 0) {
        when (numFireballs) {
            in 1..10 -> {
                inebriation += "tipsy"
            }
            in 11..20 -> {
                inebriation += "sloshed"
            }
            in 21..30 -> {
                inebriation += "soused"
            }
            in 31..40 -> {
                inebriation += "stewed"
            }
            else -> {
                inebriation += "..t0aSt3d"
            }
        }
    } else {
        inebriation += "sober"
    }
    println(inebriation)
}

My solution is here: GitHub - AlexeyYuditsky/TheBigNerdRanchGuide