For whatever reason, my Kotlin program won't initialize variables assigned inside a when statement. Here's the code:
import kotlin.random.Random
import kotlin.random.nextInt

val mood: String

when(Random.nextInt(1..2)) {
    1 -> {
        mood = "loud"
        println("$mood")
    }
    2 -> {
        mood = "quiet"
        println("$mood")
    }
}

println("$mood")

The lines inside the when statement are printed, but when I run the last line, I get a "Variable 'mood' must be initialized" error.
I don't know what I could possibly be doing wrong here...

Can't initialize variables inside of when statement in Kotlin
In Kotlin, variables declared with the val keyword must be initialized at the point of declaration or in the constructor of the class. In your code, the mood variable is declared without an initial value, and you are trying to assign values to it inside the when statement. However, the compiler is unable to determine if either of the branches will be executed at runtime, so it doesn't consider the variable as fully initialized.
To fix this issue, you can either declare the mood variable as a var instead of a val or assign an initial value to it when declaring it. Here's an updated version of your code using a var:
import kotlin.random.Random
import kotlin.random.nextInt
var mood: String

when (Random.nextInt(1..2)) {
    1 -> {
        mood = "loud"
        println("$mood")
    }
    2 -> {
        mood = "quiet"
        println("$mood")
    }
}

println("$mood")

By using a var instead of a val, you indicate that the variable can be reassigned later. Since the mood variable is assigned within both branches of the when statement, the compiler no longer complains about it being uninitialized.
Note that the order of the when branches should cover all possible cases, otherwise you might encounter a "when expression must be exhaustive" warning. In your case, the range of nextInt is 1 to 2, so the two branches should be sufficient.
