Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 337
Adam Avatar asked Apr 01 '19 11:04

Adam


People also ask

Can Java call Kotlin library?

Kotlin code can be easily called from Java. For example, instances of a Kotlin class can be seamlessly created and operated in Java methods.

Can Java access code written in Kotlin?

 Yes. Kotlin is 100% interoperable with the Java programming language and major emphasis has been placed on making sure that your existing codebase can interact properly with Kotlin. You can easily call Kotlin code from Java and Java code from Kotlin.

Does Kotlin have public fields?

Properties and fields terminologies in Kotlin sometimes is a bit confusing because technically, Kotlin doesn't have Fields. You can't declare a field. Everything is Properties!


1 Answers

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.

like image 133
Alexey Romanov Avatar answered Sep 25 '22 21:09

Alexey Romanov