Search⌘ K

Properties of Classes

Explore Kotlin's approach to class properties including implicit getters and setters, constructor properties, and how Kotlin simplifies encapsulation compared to Java. Understand how property access remains consistent regardless of custom logic, reducing the need for refactoring.

Overview

Classes in Kotlin have properties, rather than simple fields, with implicit and automatically generated getters and setters. Calling these getters and setters does not look syntactically different than direct field access in Java.

Boilerplate code in Java

A common source of unnecessary boilerplate code in Java are getters and setters for the fields of a class:

Java
public class Pet {
private String name;
private Person owner;
public Pet(String name, Person owner) {
this.name = name;
this.owner = owner;
}
// from here on only boilerplate code
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Person getOwner() {
return owner;
}
public void setOwner(Person owner) {
this.owner = owner;
}
}

Of course, we could just set the fields name and owner to public and get rid of the getters and setters. This would remove the boilerplate code, and the access to the fields would be more elegant. As we can see, the first snippet is more compact than the second:

pet.name = "Simba";
pet.setName("Simba");

While this would not be a problem in this example, especially for name, this could quickly become one with owner ...