The accessing of properties is an interesting example of the differences inherent in using a Kotlin class from either Kotlin or Java. To illustrate this, we'll once again define the following Person class:
open class Person(val firstName: String, val lastName: String)
As we discussed previously in Chapter 5, Modeling Real-World Data, Kotlin properties do not require explicit getters and setters as they will be generated automatically by the compiler. When accessing properties from Kotlin, it's a general convention to use property access syntax and reference the property names directly. But how does this work from Java?
When consuming a Kotlin class from Java, we cannot use property access syntax. However, we can make use of the generated getters and setters. In the Person example, we have getters available to us for each of the defined properties. In the following snippet, we can see how properties in the Person class can be accessed from Java:
public static void main(String[] args) {
Person person = new Person("John", "Smith");
person.getFirstName();
person.getLastName();
}
The getters available when consuming Person from Java are generated by the Kotlin compiler. Unless otherwise specified, the compiler will generate getters from any var or val property in our class.
The lack of property access in Java is an important interop difference when working with Kotlin and Java. Another important difference in the languages is in how to handle null when crossing language boundaries, which we will explore in the next section.