14

In Java, We can do this:

public class TestA {
    public static final boolean flag = true;
    public static final String str = flag ? "A" : "B"; // ok
}

But cannot in Kotlin

 class TestA {
    companion object {
        const val flag = true
        const val str = if (flag) "A" else "B" //err: Const 'val' initializer should be a constant value

        val str2 = if (flag) "A" else "B" //ok, but not equals [public static final] in Java.
    }
}

Tried @JvmStatic on non-const str2, but decompiled to java code, it's

private static final String str2 = "A"
public static final String getStr2() {
      return Companion.getStr2();
   }

Problem: kotlin if-else equals ?: in java,but cannnot use for const val. need solution for this.

1 Answers1

26

In Kotlin, const keyword should only be used when value is compile time constant. In your case it is not(const val str = if (flag) "A" else "B"). You are using if condition to pass value to str on a condition that is not compile time constant.

So you just remove const keyword and it will work perfectly. Because val creates immutable variables same as final in Java. But there is a tradeoff, if const is removed. It will under the hood generates unnecessary object and getter for accessing that variable. To solve this issue use @JvmField annotation and you are good to go.

To read more go to Where Should I Keep My Constants in Kotlin?

Hope it helps.

chandil03
  • 14,047
  • 5
  • 43
  • 64
  • 1
    non-const val with @JvmField will not create getter, it's **public static final**, that what I'm looking for! thx. –  Sep 29 '17 at 06:58
  • Hey @chandil03, In a "kotlin-app" project I can use "const val ID = R.layout.xyz" without a problem, but in a "java+kotlin" library project that snippet throws the same error. Any idea ? Thanks – hcknl Feb 06 '19 at 12:03