(Beginner) Why does this example code print kotlin.unit?

Hi all,

I am working through Kotlin in action and have the following code

enum class Color (
    val r: Int, val g:Int, val b:Int

) {
    RED(255,0,0), ORANGE(255,165,0),
    YELLOW(255,255,0), GREEN(0,255,0), BLUE(0,0,255),
    INDIGO(75,0,130), VIOLET(238,130,238);

    fun rgb() = (r * 256 + g) * 256 + b;
}

fun getMnemonic(color:Color)   {
    when (color) {
        Color.RED -> "Richard"
        Color.ORANGE -> "Of"
        Color.YELLOW -> "York"
        Color.GREEN -> "Gave"
        Color.BLUE -> "Battle"
        Color.INDIGO -> "In"
        Color.VIOLET -> "Vain"

    }
} 

My question is in main I do the following, but I get see the result “kotlin.unit” rather than the expected string value

fun main (args: Array<String>) {
    println(getMnemonic(Color.RED))
}

Why does Kotlin fail to infer the return type here ? If I change the getMnemonic method to return a string explicity, then it works.

You’d have to specify the function type as String. When using curly braces, Kotlin automatically infers that your function returns Unit.

If you don’t want to specify it, you can just use = instead:

fun getMnemonic(color: Color) = when (color) {
    Color.RED -> "Richard"
    Color.ORANGE -> "Of"
    Color.YELLOW -> "York"
    Color.GREEN -> "Gave"
    Color.BLUE -> "Battle"
    Color.INDIGO -> "In"
    Color.VIOLET -> "Vain"
}
1 Like

Ah stupid typo - it is indeed ‘=’ in the book. But a good learning point. Many thanks !

1 Like