In Java, We can do this:

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

但不能在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.

推荐答案

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.

要阅读更多内容,请点击Where Should I Keep My Constants in Kotlin?

希望能有所帮助.

Kotlin相关问答推荐

在Kotlin中,我是否可以访问已知的WHEN子句值?

Scala性状线性化等价于Kotlin

Kotlin 基于参数类型的返回类型推断

用于将 0.5 变为 0 的 round() 函数的模拟

有什么方法可以要求在 kotlin 中的类型参数上进行注释?

返回 kotlin 中的标签和 lambda 表达式

为什么这个 Kotlin 代码不起作用? (如果 str[index] 在列表中,则打印)

KMM:编译失败:意外的 IrType 类型:KIND_NOT_SET

Kotlin 从其他类调用成员扩展函数

添加 Kapt 插件后 - 执行 org.jetbrains.kotlin.gradle.internal.KaptExecution 时发生故障

如何使用 Hilt 注入应用程序:ViewModel 中的上下文?

找不到引用的类 kotlin.internal.annotations.AvoidUninitializedObjectCopyingCheck

有没有办法重用 Job 实例?

Kotlin - 当表达式返回函数类型

如何使用 gradle 脚本 Kotlin 构建文件构建可运行的 ShadowJar?

为什么 Dialog 没有 NavController [Missing]?

如何在 Gradle Kotlin DSL 中使用来自 gradle.properties 的插件版本?

Kotlin中的嵌套let块

将协程更新到 1.2.0 后构建失败:META-INF/atomicfu.kotlin_module

如何修复未解析的参考生命周期范围?