What are Properties in Kotlin?
Properties in Kotlin:
Properties are equivalent to fields in Java, but much more powerful. It’ll do the work of a field plus a getter plus a setter. Let’s see an example to compare the difference. This is the code required in Java to safely access and modify a field:
public class Person { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } ... Person person = new Person(); person.setName("name"); String name = person.getName();
In Kotlin, only property is required:
class Person { var name: String = "" } val person = Person() person.name = "name" val name = person.name
If nothing is specified, the property uses the default getter and setter. It can, of course, be modified to run whatever custom behaviour you need, without having to change the existing code:
class Person { var name: String = "" get() = field.toUpperCase() set(value) { field = "Name: $value" } }