Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 134 ยท Classes and Objects

Classes and Properties

Learn Kotlin classes: primary constructors, val and var properties, custom getters and setters, backing fields, init blocks, member functions and common mistakes, with runnable code.

A class is a blueprint for objects that bundle data with the functions that work on that data. A BankAccount holds a balance and knows how to deposit; a Player holds a name and a score and knows how to level up. Kotlin classes are much shorter than their Java equivalents because the language puts the constructor, the fields and the accessors into a few words.

In this lesson you build classes from the ground up: the primary constructor, properties (not fields), custom getters and setters, the hidden backing field, init blocks, and member functions. By the end you will know exactly what the compiler generates from class Person(val name: String) and why Kotlin code almost never needs getName() and setName().

Your first class

Kotlin A first class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Look at what is missing compared with other languages: there is no new keyword (you call the class like a function), and no explicit field, constructor or getter. class Dog(val name: String, var age: Int) does all of it:

  • The part in parentheses is the primary constructor. Writing val or var in front of a parameter turns it into a property of the class.
  • val name is read-only (set once, like a Java final field plus a getter). var age is mutable (a getter and a setter).
  • The body in braces holds member functions and more properties.

Outside the class you read rex.name and write rex.age = 4. These look like direct field access, but they call generated accessor methods, which is why you can later add logic to them without changing a single caller.

A class with no body needs no braces: class Marker is a valid, empty class. A primary constructor with no parameters can also be left out entirely.

Properties versus fields

Java programmers think in fields plus hand-written getters and setters. Kotlin has properties instead, and a property is the whole package: a name, a type, a getter, an optional setter and, if needed, a hidden field to store the value.

Parameters of the primary constructor that are not marked val or var are plain parameters. They exist during construction only and are not kept as properties:

Kotlin Constructor parameter versus property (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler stops with main.kt:2:32: error: unresolved reference 'name'. because name is only a constructor parameter and member functions cannot see it. Add val in front of it to make it a property (or copy it into a property in an init block, as shown below).

Declaring properties in the body

Not every property comes from the constructor. You can declare more inside the class, and they need an initial value (or a getter, or lateinit, which you meet in Advanced Properties):

Kotlin Properties declared in the body

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

This prints 0 true and then 2 false. Two ideas appear here:

  • var count = 0 with private set makes a property that everyone can read but only the class can change. This is the Kotlin way to protect state, without a manual getter and setter pair.
  • isZero has no stored value at all. It is a computed property: get() = count == 0 runs every time you read it.

Try to assign c.count = 5 from main and the compiler answers error: cannot access 'count': it is private in 'Counter'.

Custom getters and setters

A property can define its own accessors. The setter receives the new value as a parameter (conventionally called value) and, inside an accessor, the special identifier field refers to the backing field where the data actually lives:

Kotlin Custom setter with validation and a backing field

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Setting 99 stores 30 and setting -5 stores 10, so the lines print 25, 30, 10, and finally HOME. The setter clamps the incoming value with coerceIn before writing it to field.

The backing field exists only when the property uses at least one default accessor or mentions field in a custom one. This matters because writing target = value inside the setter of target would call the setter again, forever. That mistake ends in a stack overflow:

Kotlin Setter calling itself (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The program compiles without a warning, then dies with Exception in thread "main" java.lang.StackOverflowError. The fix is the one-word change size = value to field = value. As a rule: inside an accessor, always use field for the stored value.

init blocks and initialization order

The primary constructor cannot contain code, only parameters. For validation or setup, a class uses one or more init blocks. They run in the order they appear, interleaved with property initializers, each top to bottom, when you create an object:

Kotlin Initialization order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first object prints init 1: id=1, total initialised and init 2: total=30. The second prints only init 1: id=2 and then fails in require, so rejected: quantity must be positive, was 0 follows. Two lessons here:

  1. Initializers and init blocks run strictly in source order. A block can only use properties declared above it. Reading a property that is initialized later gives you its default (0, null) at best, and the compiler rejects most such cases.
  2. Validating in init with require guarantees that an invalid object never exists. Callers get an IllegalArgumentException. See require, check and assert.

Constructors get their own lesson, Constructors, including secondary constructors and default values.

Member functions and this

Functions declared in a class are member functions (methods). Inside them this is the current object, though you only need to write it when a name is ambiguous:

Kotlin Member functions, this and chaining

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Returning this allows chaining like scale(2.0).scale(0.5). For a quick "configure an object" pattern Kotlin has a neater tool, apply (see Scope Functions).

Classes are final and objects are references

Two defaults to remember. First, a Kotlin class is final: nobody can inherit from it unless you write open class (see Inheritance). Second, a variable that holds an object holds a reference: assigning it to another variable shares the same object.

Kotlin Two names for one object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Output: lamp, false, true. The class has no equals of its own, so == falls back to identity, and two boxes with the same content are not equal. Writing a meaningful equals by hand is tedious, which is exactly what data classes are for. Equality and Identity explains == versus === in depth.

Note that val b = a does not stop b.content = "lamp": val makes the variable unchangeable, not the object. To forbid changes to the object, declare its properties val too.

Design notes and common mistakes

  • Prefer val. An object whose properties never change is far easier to reason about, to share between threads and to use as a map key. Reach for var when state really changes.
  • Do not copy Java habits. Never write fun getName() for a property named name; the compiler reports error: platform declaration clash: The following declarations have the same JVM signature (getName()Ljava/lang/String;), because the property already generates that getter. Add a property instead.
  • Computed or stored? A property that is cheap to compute from others (isZero, area) is better as a getter than as a second stored value that can go stale.
  • Keep init blocks short. Heavy work in a constructor makes objects slow and hard to test; use a factory function for complex setup.
  • A setter that rejects bad data is a design choice. Silent clamping (as in the thermostat) hides mistakes; throwing from the setter makes them visible. Decide which one your callers deserve.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the effect of writing val in front of a primary-constructor parameter?

    val (or var) in the primary constructor declares a property. Without it the parameter exists only during construction.
  2. 2. Inside a custom setter, which assignment stores the value without causing infinite recursion?

    field is the backing field. Assigning to the property name inside its own setter calls the setter again.
  3. 3. In what order do property initializers and init blocks run?

    They are executed in source order, so a block can only rely on properties declared above it.
  4. 4. Given class Box(var content: String), what does Box("a") == Box("a") print?

    Plain classes inherit identity-based equals from Any. A data class would generate value-based equality.
  5. 5. What does var count = 0 followed by private set give you?

    The getter keeps the default public visibility while the setter is restricted to the class.

Summary

  • class Name(val a: Int, var b: String) declares a class, a primary constructor and properties in one line; there is no new.
  • A property is a name, a type, a getter, an optional setter and, when needed, a backing field. Use val for read-only and var for mutable.
  • Custom accessors can validate or compute; use field inside them, and private set to restrict writing.
  • init blocks and property initializers run in source order; validate with require so invalid objects never exist.
  • Classes are final by default, and variables hold references; val protects the variable, not the object.

Next: Constructors