Member-only story
Understand Fields and Properties in Kotlin
How Kotlin implicitly implements field, getter and setter function for you when you declare a property?
3 min readAug 20, 2022
Properties and fields terminologies in Kotlin sometimes is a bit confusing because technically, Kotlin doesn’t have Fields. You can’t declare a field. Everything is Properties!
However, to avoid confusion, I prefer to define Fields and Properties separately based on the following:
- Fields are private member variables of a class. Memory is allocated.
- Properties are public or protected getter or setter functions which allow you to access to the private fields.
I like to define like this because it helps my understanding and it also makes things a lot easier to explain.
Implicit Field, Implicit Getter/Setter
Let’s look at this example. name
is a property.
class Person {
var name = "Vincent"
}
When you declare a property like this, Kotlin implicitly creates field, getter and setter functions for you.
In Java decompiled code, it looks like this:
public final class Person {
@NotNull
private String name = "Vincent"…