June 2018
Intermediate to advanced
310 pages
6h 32m
English
Up until now, we were always using the primary constructor of the class. That's the one declared after the class name. But in Java, we can define more than one constructor for a class. Why does Kotlin limit us to only one?
Actually, it doesn't. We can define secondary constructors for a class using the constructor keyword:
class Squad(val infantryUnits: MutableList<InfantryUnit> = mutableListOf()) { constructor(first: InfantryUnit) : this(mutableListOf()) { this.infantryUnits.add(first) } constructor(first: InfantryUnit, second: InfantryUnit) : this(first) { this.infantryUnits.add(second) } constructor(first: InfantryUnit, second: InfantryUnit, third: InfantryUnit) : this(first, second) { this.infantryUnits ...
Read now
Unlock full access