Skip to content

Annotations in kotlin ‐ @JvmField

Devrath edited this page Oct 12, 2023 · 2 revisions

Observation

  • Note the name variable is annotated as @JvmField.
  • This indicated to the compiler that this field can directly accessed by the java class.
  • Note the java class will not need the getter method to access it.
  • It can be done the same way the kotlin class would do it.

Code

Person.kt

data class Person(@JvmField val name: String, val age:Int)

DemoKotlinJvmAnnotation.kt

class DemoKotlinJvmAnnotation {
    fun initiate() {
        val person = Person("Suresh", 23)
        PrintUtils.printLog(person.name)
        PrintUtils.printLog(person.age.toString())
    }
}

DemoJavaJvmAnnotation.java

public class DemoJavaJvmAnnotation {
    public void initiate() {
        // Compiler will understand getter and setter will not be needed and we can access the field directly
        Person person = new Person("Suresh",23);
        PrintUtils.INSTANCE.printLog(person.name); // Observe we have not used the getter method still able to access the field
        PrintUtils.INSTANCE.printLog(String.valueOf(person.getAge())); // Since the JVM annotation is not present for this field, We need a getter method to access the field
    }
}
Clone this wiki locally