You might have noticed that, in the previous example, we were able to access the newly added title property without having added a getter. This is possible because Kotlin will generate getters and setters for us for properties with simple accessor logic. Let's look more closely at the following code:
In this snippet, we have our Course class with a public title property:
class Course(courseTitle: String) {
val title = courseTitle
}
From Kotlin, we can access that property name directly, as follows:
val courseTitle = course.title
However, from Java, we must access that property using a generated getter:
String courseTitle = course.getTitle();
From Kotlin, we can access the property by referencing its name directly without any kind of get/set prefix. This is known as the property access syntax and is syntactic sugar around using getters/setters generated by the compiler. What makes the property access syntax possible is the fact that the Kotlin compiler will generate default getters and setters for any var properties on a class and will generate getters for any val properties.
In the following code, we can see the decompiled Kotlin bytecode for the Course class we've been looking at:
public final class Course {
@NotNull
private final String title;
@NotNull
public final String getTitle() {
return this.title;
}
public Course(@NotNull String courseTitle) {
Intrinsics.checkParameterIsNotNull(courseTitle, "courseTitle");
super();
this.title = courseTitle;
}
}
We'll see here that the public read-only title property becomes a private final member and a getTitle() method is generated that allows that title property to be read.
In this example, we'll add a new read/write property, description:
class Course(courseTitle: String) {
val title = courseTitle
var description = ""
}
After adding this additional property, the compiler will add any required getters/setters. The following snippet illustrates the getter that is generated as a result of adding the description property:
...
@NotNull
public final String getDescription() {
return this.description;
}
public final void setDescription(@NotNull String var1) {
Intrinsics.checkParameterIsNotNull(var1, "<set-?>");
this.description = var1;
}
...
By generating getters and setters for simple properties, Kotlin is writing the boilerplate for us, which saves us code and time. However, it's still possible for us to have more control over the get and set operations for our properties. We'll take a look at how to customize these getters and setters in the following section.