Mikhail
Mikhail

Reputation: 3746

Using kotlin constants in java switch expression

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.

Upvotes: 15

Views: 6480

Answers (2)

Eric Liu
Eric Liu

Reputation: 1536

A even more simple solution would be: to declare the constants in the 'Kotlin file' instead of 'Kotlin class', which is basically declaring the constants outside the class scope and they can be referenced anywhere with proper imports.

const val CONSTANT_ONE = 1
const val CONSTANT_TWO = 2

class Service {
}

Or if you want something that's similar to private static final int CONSTANT_ONE = 1;

You can declare the constants to be private in Kotlin file, and only classes within the same file have accesses to it.

private const val CONSTANT_ONE = 1
class A{
   // can access CONSTANT_ONE
}

class B{
  // can access CONSTANT_ONE
}

Upvotes: 0

Jeremy Lyman
Jeremy Lyman

Reputation: 3234

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.

Upvotes: 25

Related Questions