I've been looking into Kotlin lang recently and its interop with java. I have following java code:
public void select(int code) {
switch code {
case Service.CONSTANT_ONE:
break;
case Service.CONSTANT_TWO:
break;
default:
break;
}
}
Where Service.kt
written as follows:
class Service {
companion object {
val CONSTANT_ONE = 1
val CONSTANT_TWO = 2
}
}
Java compiler says that CONSTANT_ONE and CONSTANT_TWO must be constants, but I don't know, how I can make them more constant than they are now. So my question is: how to use constants from kotlin in java swicth statement?
I'm using jdk8 and kotlin M14.
The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal. When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
Android App Development for Beginners In Kotlin too, we have a keyword to create such a variable whose value will remain as constant throughout the program. In order to declare a value as constant, we can use the "const" keyword at the beginning.
The Kotlin language does not have any switch statement. Instead, it supports a much simpler when statement. It is the Kotlin equivalent to Java's switch statement. The idea behind replacing the switch statement in Kotlin is to make the code easier to understand.
Kotlin does not provide an option to write a switch-case statement; however we can implement the switch-case functionality in Kotlin using the when() function which works exactly the same way switch works in other programming languages.
M14 changes state "Since M14 we need to prefix Kotlin constants with const to be able to use them in annotations and see as fields from Java"
class Service {
companion object {
const val CONSTANT_ONE = 1
const val CONSTANT_TWO = 2
}
}
IntelliJ still shows me an error in the Java case but it compiles and works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With