kotlinkotlin-java-interop

Access kotlin public field from Java directly without getter


Below is a example of a pattern from Android (Just an example, not interested in android specifics):

/*Im a kotlin file*/
class ListItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    val text: = itemView.my_view
}

Then the pattern is that you access the text field as such:

/*Im a Java file*/
holder.text.setText("Metasyntactic variable");

It's unfortunate to have a large file with a set structure doing the above and then have:

/*Im a Java file, but this particular holder is a kotlin file*/
holder.getText().setText("Metasyntactic variable");

Is it possible to solve this? Maybe with some @Jvm annotation


Solution

  • It's @JvmField:

    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.