Using existing code

We can easily instantiate and manipulate Java classes from Kotlin. Let's revisit the Programmer class written in Java:

public class Programmer extends Person {
private String preferredLanguage;

public Programmer(String firstName, String lastName,
String preferredLanguage) {
super(firstName, lastName);
this.preferredLanguage = preferredLanguage;
}

public String getPreferredLanguage() {
return preferredLanguage;
}
}

We can instantiate this from Kotlin like so:

val programmer = Programmer("John", "Smith", "Kotlin")

An interesting side effect of using a Java class from Kotlin is that we can take advantage of property access syntax to access fields exposed via getters/setters without having to actually call the getters and setters.

Note that in this snippet, we can access all the properties of Programmer using property access syntax, regardless of whether they were originally defined in Kotlin or Java:

val programmer = Programmer("John", "Smith", "Kotlin")
programmer.preferredLanguage
programmer.firstName

In this code snippet, we are only able to access preferredLanguage because we exposed a getPreferredLanguage() method. The field itself is private, but the Kotlin compiler will generate a synthetic accessor based on a getter if it detects one, thereby allowing us to use property access syntax.

Synthetic accessors are just one area where the Kotlin compiler does a lot of work behind the scenes to make our code more concise and convenient. Another such area is in the strict enforcement of nullability; however, when working across both Kotlin and Java, some of this strict type information can be lost. In the next section, we'll shed some more light on this occurrence.