如何在 Kotlin 中创建没有访问器的 属性?

How to create a property without accessors in Kotlin?

我正在使用来自 Java 代码的 Kotlin class。我的 Kotlin class 看起来像:

class Something {
    var a = 0
}

我希望能够从 Java 代码访问 a,例如

s = new Something();
s.a = 5;

然而,我只有s.getA()s.setA(5)。有什么方法可以让 属性 直接从 Java 设置和获取吗?显然在这种情况下我们不能自定义 getter 和 setter。

您可以使用 @JvmField annotation 注释 属性 以将其公开为 Java 字段。

If you need to expose a Kotlin property as a field in Java, you need to annotate it with the @JvmField annotation. The field will have the same visibility as the underlying property. You can annotate a property with @JvmField if it has a backing field, is not private, does not have open, override or const modifiers, and is not a delegated property.