Creating and working with Java classes from Kotlin

The following snippet illustrates a simple Java class with two fields and associated getters:

// basic Java class
public class Developer {
private String name;
private String favoriteLanguage;

public Developer(String name, String favoriteLanguage) {
this.name = name;
this.favoriteLanguage = favoriteLanguage;
}

public String getName() {
return name;
}

public String getFavoriteLanguage() {
return favoriteLanguage;
}
}

This Developer class is representative of any simple model object representing a person. Even though Developer is implemented in Java, we can still use it from Kotlin, as demonstrated in the following snippet:

// Kotlin function creating a new Developer object and accessing the 'name'
fun main(args: Array<String>) {
val kotlinDev = Developer("Your Name", "Kotlin")
val name = kotlinDev.name
}

From Kotlin, we are still able to fully use an existing Java class and all of its methods. This means you don't need to convert existing Java classes into Kotlin before being able to use them in your Kotlin code. This makes Kotlin highly interoperable with existing Java code bases and tooling.

Notice how, in the preceding snippet, the name field was accessed without calling .getName()? This is known as the property access syntax and allows you to access a property value directly rather than calling the getter. You'll learn more about this in Chapter 5Modeling Real-World Data.