Kotlin Easy · Lesson 1 · On the house

Classes and properties

class, val/var properties, methods, instances. Lesson 1 is free — on the house.

Lessons · Kotlin Easy · Lesson 1 of 10 · On the house

Classes and properties

class, val/var properties, methods, instances.

Illustration for Kotlin
Lesson 1 is on the house.

A Kotlin class groups state and behaviour. class Person(val name: String) declares a class whose primary constructor property name is a read-only val on every instance.

Properties declared with val expose a getter only. Properties declared with var expose a getter and a setter. You can also declare properties in the class body: var age: Int = 0.

Methods are ordinary fun members inside the class. Call them on an instance: p.greet(). Inside a method, this refers to the current instance; you may omit this. when the name is unambiguous.

Create an instance with the constructor call syntax — no new keyword: val p = Person("Ada"). Each call allocates a distinct object unless you use an object singleton (covered later).

Misses: writing new Person(...) (Java), putting types before names (String name), or treating a class name as a value without constructing an instance.

classes

class Person(val name: String) {
    var age: Int = 0
    fun greet(): String = "hello, $name"
}

fun main() {
    val p = Person("Ada")
    p.age = 36
    println(p.greet())
    println(p.age)
}
Match this when you type.

Quiz

How do you construct a Kotlin class instance?

Quiz

What does a val property on a class expose?

Quiz

Where can you declare class properties?

Quiz

Inside an instance method, what does this refer to?

Check

Match the still for: Classes and properties.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.