/** * Parameter passing in Kotlin and immutability. * The question of immutability really only applies to containter * objects. Eg, arrays, lists, ... */ //very basic class -- really does nothing much more than exists open class A(var aa:Int) { // tostring method shows what class it is override fun toString() = this.javaClass.simpleName } // inherits from A open class B(aa:Int, var bb:Int) : A(aa) {} // also inherits from A open class C(aa:Int, var cc:Int) : A(aa) {} fun main() { val lb = mutableListOf() lb.add(B(5,6)) val la = mutableListOf() la.add(A(1)) la.add(B(2,3)) la.add(C(3,4)) rA(lb) rA(la) //rAM(lb) // not allowed by compiler rAM(la) rAMA(la) rAMA(lb) rSTAR(la) rSTAR(lb) } // because list is mutable, can only take list of A // if allowed mutability, then could add an object of type A to the // list, but the list could have been declared to only hold type B fun rAM(loa : MutableList) { println("RAM %s".format(loa)) } // in this version, List is immutable, // so the compiler allows passing in of list of A or B fun rA(loa : List) { println("RA %s".format(loa)) } // Mutable list, but the "out" projection make it immutable!!! // Why not just say this is a List!!! // Because there may be a container that does not have both // mutable and immutable forms fun rAMA(loaa : MutableList) { // equivalent to Java println("RAMA %s".format(loaa)) //loaa.add(A()) // because it is declares as "out" the add operation not allowed //loaa.add(B()) } // Mutable list but the "star projection" makes it immutable. fun rSTAR(loaa : MutableList<*>) { // Anything can come in, but cannot write to it. Effectively immutable. println("RSTAR %s".format(loaa)) //loaa.add(A()) //loaa.add(B()) }