/** * Object copying in Kotlin (also mostly applies to Java) * @author gtowell * Created: August 2021 * modified: Nov 12, 2021 */ // a simple data class with two vals and a var data class ttt(val aa:Int, val bb:Int, var cc:Int) // a simple class with two vals and a var class tt(val aa:Int, val bb:Int, var cc:Int) { // a copy constructor constructor(told:tt) : this(told.aa, told.bb, told.cc) // a copy function thtat is totally equivalent to the copy constructor fun gtcopy() = tt(this.aa, this.bb, this.cc) override fun equals(other:Any?) = (other is tt) && (other.aa == this.aa) && (other.bb == this.bb) && (other.cc == this.cc) override fun toString() = "tt(%d %d %d)".format(aa,bb,cc) } // Testing the copy function that exists by default for data classes fun tttest() { val aa = ttt(1,2,3) val bb = ttt(1,2,3) val cc = aa.copy() println("aa bb ==${aa==bb} ===${aa===bb}") println("aa cc ==${aa==cc} ===${aa===cc}") } // testign the two copy functions written for non data class fun ttest() { val aa = tt(1,2,3) val bb = tt(1,2,3) //val cc = aa.copy() //only defined for data class val cc = tt(aa) val dd = aa.gtcopy() println("aa aa ==${aa==aa} ===${aa===aa}") println("aa bb ==${aa==bb} ===${aa===bb}") println("aa cc ==${aa==cc} ===${aa===cc}") println("aa dd ==${aa==dd} ===${aa===dd}") } // Now for lists fun cop() { // first create a mutable list and then a slice of that list val lst = mutableListOf(1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9) val sli = lst.slice(5..12) println(lst) println(sli) // change an item in the list. // the item in the slice is unchanged lst[8]=88 println(lst) println(sli) // create a list of mutable objects, slice as before // this time change the internals of the object val lst2 = listOf(tt(1,2,3), tt(2,3,4), tt(3,4,5), tt(4,5,6)) val sli2 = lst2.slice(1..2) println(lst2) println(sli2) lst2.get(2).cc=88 println(lst2) println(sli2) } fun main() { tttest() ttest() cop() }