classes - TonyGuyot/kotlin-notes GitHub Wiki

Classes and inheritance

Defining classes

Minimal class declaration:

    class Empty

Class with a primary constructor:

    class Person(name: String)

Class with a primary constructor and initialization code:

    class Person(name: String) {
        init {
            // here name can be used
        }
    }

Class with a primary constructor and a property. The property definition can reference parameters from the constructor:

    class Person(name: String) {
        val key = name.capitalize()
    }

Using the primary constructor to declare and initialize properties with val and var keywords:

    class Person(val name: String)

Creating instances

Works as a function call (no need of a new keyword):

    val empty = Empty()
    val person = Person("John Doe")

Defining data classes

Data classes will have equals(), hashCode(), toString() and copy() automatically generated, unless they are explicitly defined in the class:

    data class Person(val name: String = "", val age: Int = 0)

Defining generic classes

Classes may have type parameters:

    class Box<T>(t: T) {
        var value = t
    }

The type has to be provided when creating an instance:

    val box: Box<Int> = Box<Int>(1)

Unless it can be inferred from the argument:

    val box = Box(1)

Inheritance

By default, a class inherits implicitly from superclass Any (which is different than java.lang.Object). To derive explicitly from a superclass:

    open class Base(a: Int)
    class Derived(a: Int) : Base(a)

Note: the primary constructor of the superclass has to be called. The superclass must be declared with the open keyword, otherwise it is considered final.

To override methods, they must also be declared with open in the superclass and the override keyword must be used in the subclass:

    open class Base {
        open fun f() {} // can be overridden in subclasses
        fun g() {} // cannot be overridden
    }
    class Derived(a: Int) : Base(a) {
        override fun f() {}
    }

Singletons

To define a singleton:

    object Singleton {
        val name = "Name"
    }
⚠️ **GitHub.com Fallback** ⚠️