What is the difference between Java field and Kotlin property?

Technology CommunityCategory: KotlinWhat is the difference between Java field and Kotlin property?
VietMX Staff asked 3 years ago

This is an example of a Java field:

public String name = "Marcin";

Here is an example of a Kotlin property:

var name: String = "Marcin"

They both look very similar, but these are two different concepts. Direct Java equivalent of above Kotlin property is following:

private String name = "Marcin";
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}

The default implementation of Kotlin property includes field and accessors (getter for val, and getter and setter for var). Thanks to that, we can always replace accessors default implementation with a custom one.