Is there a way to get the value of the expression I passed into the when
statement?
In my application I have a KeyListener
like that
_content.addKeyListener(object : KeyAdapter() {
override fun keyPressed(e: KeyEvent?) = when(e?.keyCode) {
KeyEvent.VK_T -> mainWindow.enterTrainingState()
KeyEvent.VK_P -> mainWindow.enterPlayState()
KeyEvent.VK_E -> mainWindow.close()
else -> println(e?.keyCode)
}
})
Has Kotlin a neat syntax to access e?.keyCode
? I don't really want to repeat the expression.
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)
}
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)
}
}