How to hide Kotlin lateinit var backing field from Java?

In Kotlin, suppose I have a class:

class MyKotlinClass { lateinit var field: String } 

According to the docs :

Late initialized objects are also displayed as fields. The visibility of the field will be the same as the visibility of setting lateinit properties.

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

How can I achieve this and save the lateinit modifier?

+7
java kotlin
source share
3 answers

You can use @JvmSynthetic , which hides ads from Java (and not from Kotlin). Just annotate the property background field :

 @field:JvmSynthetic lateinit var field: String 

Although the field will remain public in bytecode, it will also have a synthetic modifier that prevents it from being used in Java sources. However, the field is apparently still accessible through reflection at runtime.

See also: another question about @JvmSynthetic (although there is no specific answer there).

+12
source share

A classic solution to this problem would be to use property delegation :

 import kotlin.properties.Delegates class MyKotlinClass { var field: String by Delegates.notNull() } 

This code does exactly what you asked in the question

+2
source share

The visibility of the lateinit field is lateinit from the visibility of the setter of the corresponding property, so another option is to have a property with a non-public setter:

 lateinit var field: String private set 

The disadvantage of this approach is that the setter itself becomes inaccessible outside the class.

+1
source share

All Articles