17

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 Answer 1

33

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.

3
  • 1
    non-const val with @JvmField will not create getter, it's public static final, that what I'm looking for! thx.
    – user4003256
    Sep 29, 2017 at 6: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 6, 2019 at 12:03
  • 1
    "const keyword should only be used when value is compile time constant" I mean, this is exactly the problem, in my opinion an if with a constant condition and only constant return values should be a compile time constant.
    – Nyde
    Dec 4, 2022 at 13:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy