1

I'm intrigued by kotlin's when statement. It seems almost as powerful as the lisp cond, but not quite. In one example on the kotlin web site here, you can see that there is no subject. You just list boolean expressions, and the first one to succeed is evaluated, just like lisp's cond.

when {
    handler == null -> print("null")
    else -> print("handler is valid")
}

But this generates a compiler warning, saying when 'with' subject should be used. How can I use this construct without generating compiler warnings?

SMBiggs
  • 11,034
  • 6
  • 68
  • 83

2 Answers2

2

I think I figured it out.

The compiler is smart, very smart. It recognizes that my when is only using one variable, handler. The warning is telling me that the variable should be used as the subject of the when as in this example:

when (handler) {
    it == null -> print("null")
    else -> print("handler is valid")
}

But if I use more than one variable, the warning goes away. The compiler seems to recognize that a subject doesn't make sense. Here's an example:

when {
    firstHandler == null -> print("first handler is null")
    secondHandler == null -> print("second handler is null")
    else -> print("handlers are both valid")
}

No warning is produced as there is no single subject.

SMBiggs
  • 11,034
  • 6
  • 68
  • 83
0

It is good practice to use the 'with' subject (the parameter you can pass in when) for these cases. So a warning-free code would be

   when (handler) {
        null -> print("null")
        else -> print("handler is valid")
    }

Normally if you have two case, it is better to use if. But think about more cases. If you had to use handler for other conditions, passing handler as subject will make your code cleaner. (not sure if there is any performance impact on this, shouldn't be)

stinepike
  • 54,068
  • 14
  • 92
  • 112