Properties of Classes
Learn how Kotlin does a better job than Java when it comes to accessing class properties.
We'll cover the following...
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:
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 codepublic 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
, ...