Constructors
Kotlin allows us to define classes without any constructors. We can also define a primary constructor and one or more secondary constructors:
class Fruit(val weight: Int) { constructor(weight: Int, fresh: Boolean) : this(weight) { } } //class instantiation val fruit1 = Fruit(10) val fruit2 = Fruit(10, true)
Declaring properties is not allowed for secondary constructors. If we need a property that is initialized by secondary constructors, we must declare it in the class body, and we can initialize it in the secondary constructor body. Let's define the fresh
property:
class Test(val weight: Int) { var fresh: Boolean? = null //define fresh property in class body constructor(weight: Int, fresh: Boolean) : this(weight) { this.fresh = fresh //assign constructor parameter to fresh property } }
Notice that we defined our fresh
property as nullable because when an instance of the...