Property, Getter and Setter — Kotlin

This post was originally posted at and reposted on Medium on 3rd Mar 2018.
var <propertyName>: <PropertyType> = <property_initializer>
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) { = 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




Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Introduction to Openshift Operators

Recovery Software For Created Date Mac

ACC 362: Utilizing Scrum/Agile with The Bloomington Revitalization Project

A Guide to exploit Random Forest Classifier in PySpark

What To Choose AWS Or Azure For IaaS In 2021?

Shellmates Mini CTF 2018 — Write-up — Guess the token 1

The Linux Argument

On & Off Premises :

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
Suneet Agrawal

Suneet Agrawal

More from Medium

How to Use TriState Toggle in Jetpack Compose

Jetpack Compose Basics

Null Safety in Kotlin

Kotlin Flows Unit Tests

A screen shot of a popup window that helps you generate a test class