How to hide Kotlin's lateinit var backing field from Java?

Michael Spitsin :

In Kotlin, suppose, I have class:

class MyKotlinClass {
    lateinit var field: String
}

According to docs:

Late-Initialized properties are also exposed as fields. The visibility of the field will be the same as the visibility of lateinit property setter.

I can use in java code either myKotlinClass.field or myKotlinClass.getField(). I want to disable field access and remain only access through getter and setter.

How can I achieve this and remain lateinit modifier?

hotkey :

You can use @JvmSynthetic that hides declarations from Java (and not from Kotlin). Just annotate the backing field of the property:

@field:JvmSynthetic
lateinit var field: String

Though the field will remain public in the bytecode, it will also have the synthetic modifier, which prevents it from being used in Java sources. However, the field seems to be still accessible through reflection at runtime.

See also: another question about @JvmSynthetic (though no definite answer there).

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=455877&siteId=1