Kotlin: Accessing parameter of when-statement
I had this problem myself a couple of days ago. I think it would have been nice to be able to access the value as it
inside the when
-expression.
I solved it by assigning the expression to a val
before the when
expression:
val keyCode = e?.keyCode
when(keyCode) {
KeyEvent.VK_T -> mainWindow.enterTrainingState()
KeyEvent.VK_P -> mainWindow.enterPlayState()
KeyEvent.VK_E -> mainWindow.close()
else -> println(keyCode)
}
Unfortunately, this would require you to add extra braces and lines. The upside though, is that e?.keyCode
would only be evaluated once. It may not matter in this exact case, but if the expression was bigger, this approach would be suitable.
Edit:
Another possibility it to wrap the when
expression in a call to let
. It lets you access the parameter with it
. Like this:
e?.keyCode.let {
when(it) {
KeyEvent.VK_T -> mainWindow.enterTrainingState()
KeyEvent.VK_P -> mainWindow.enterPlayState()
KeyEvent.VK_E -> mainWindow.close()
else -> println(it)
}
}
Edit2:
Kotlin 1.3 has support for capturing the subject expression of a when
in a variable. This is the syntax:
when(val keyCode = e?.keyCode) {
KeyEvent.VK_T -> mainWindow.enterTrainingState()
KeyEvent.VK_P -> mainWindow.enterPlayState()
KeyEvent.VK_E -> mainWindow.close()
else -> println(keyCode)
}
It's not possible as of Kotlin 1.1. There is an open feature request for this functionality: https://youtrack.jetbrains.com/issue/KT-4895