Property, Getter and Setter — Kotlin

This post was originally posted at https://agrawalsuneet.github.io/blogs/property-getter-and-setter-kotlin/ and reposted on Medium on 3rd Mar 2018.
var <propertyName>: <PropertyType> = <property_initializer>
[<getter>]
[<setter>]
val name : String = "John"
var age : Int = 0
public final String name = "John";
public int age = 0;
  • No need to add public modifier as by default, all properties and functions are public in Kotlin. Add private or protected if required.
  • A property must be initialized or need to be declared as abstract in Kotlin . Instead, we can even use lateinit which is better explained here.
  • All properties are final by default. If you want to override some property or its getter setter, define the property as open(explained later in the same post).
private String name;public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
var name: String = “John”
Where are my getter and setter?
private int size = 0;
private boolean isEmpty;
public boolean isEmpty() {
return size == 0;
}
private val size : Int = 0var isEmpty: Boolean = false
private set
get () = size == 0
private String firstName;
private String lastName;
//private String name;public String getName() {
return firstName + " " + lastName;
}
public void setName(String name) {
String nameArray[] = name.split(" ");
firstName = nameArray[0];
lastName = nameArray[1];
}
private var firstName: String? = null
private var lastName: String? = null
var name: String
get() = firstName + " " + lastName
set(value) {
val nameArray = value.split(" ".toRegex())
firstName = nameArray[0]
lastName = nameArray[1]
}
public var name: String = "John"
private set
//Base class
open var age: Int = 0
get() = 10
//Extending class
override var age: Int = 0
get()= 20

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store