Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using kotlin constants in java switch expression

Tags:

java

kotlin

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.

like image 880
Mikhail Avatar asked Oct 13 '15 17:10

Mikhail


People also ask

Can we use constants in switch case?

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.

How do you use Kotlin constants?

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.

What is the equivalent of switch expression in Kotlin?

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.

What is the best alternative of switch case in Kotlin?

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.


1 Answers

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.

like image 171
Jeremy Lyman Avatar answered Sep 22 '22 21:09

Jeremy Lyman