/* * Class in kotlin with two constructors. Note that the "secondary" * constructor must always start by calling the primary constructor * (The primary is defined on the first line) * Note the init stuff is called by every constructor. * * @author gtowell * created: August 19, 2021 */ // open indicates you can override open class twocon(val a:String, var b:String) { override fun toString() = "a=[${a}] b=[${b}]" constructor(aa:String) : this("secondary"+aa, "hello") { println("Secondary constructor started") } init { println("Init called") } } //Problem this version makes a couple of properties that you will never use and are wasteful. class threevar(val aIH:String, val bIH:String, val c:String) : twocon(aIH,bIH) { override fun toString() = "%s: %s %s %s".format(this.javaClass.simpleName, c, aIH, b) } // declare class with NO promary constructor. // So the do extra vals are created // secondary constructor cannot have var or val!! class threevarB : twocon { val c:String constructor(aa:String, bb: String, cc:String) : super(aa, bb) { c=cc } override fun toString() = "%s: %s %s %s".format(this.javaClass.simpleName,c,a,b) } // But that is really boring so in primary constructor only // params with var/var create parameters class threevarC(aa:String, bb: String, val c:String) : twocon(aa, bb) { override fun toString() = "%s: %s %s %s".format(this.javaClass.simpleName, c,a,b) } /* class threevarD(val a:String, var b: String, val c:String) : twocon(a, b) { override fun toString() = "%s: %s %s %s".format(this.javaClass.simpleName, c,a,b) } */ fun main() { val tc1 = twocon("a", "b") val tc2 = twocon("aa") println(tc1) println(tc2) val tt1 = threevarB("a", "b", "c") println(tt1) val ttC = threevarC("a", "b", "c") println(ttC) }