Search code examples
kotlinrangeread-eval-print-loop

Why am i unable to use this simple code in my kotlin repl


I receive this error -----

error: incompatible types: IntRange and Int
3..12 -> print("Good fish name")

var fishName = "anyname"
when (fishName.length){
0 -> print("Error")
3..12 -> print("Good fish name")
else -> {
print("OK fish name")
} 
}

I was expecting to be able to have the message "Good fish name" be printed out.


Solution

  • A when construct is comparing the argument fishName.length which is an Int with each of the values in the when construct. The first 0 is an Int, but 3..12 is an IntRange; each must be an Int for the equality test.

    Here are three solutions:

    Pass in a load of Ints...

        when (fishName.length){
            0 -> print("Error")
            3,4,5,6,7,8,9,10,11,12 -> print("Good fish name")
            else -> {
                print("OK fish name")
            }
        }
    

    or use this alternate form, changing the zero test also to be a range:

        when (fishName.length){
            in 0..0 -> print("Error")
            in 3..12 -> print("Good fish name")
            else -> {
                print("OK fish name")
            }
        }
    

    UPDATE From @gidds - "Kotlin lets you mix individual values ... with predicates":

        when (fishName.length){
            0 -> print("Error")
            in 3..12 -> print("Good fish name")
            else -> {
                print("OK fish name")
            }
        }
    

    See https://kotlinlang.org/docs/control-flow.html#when-expression