使用场景:通过+号实现对象属性的叠加
class Test(var num: Int) {
operator fun plus(t: Test): Test{
num += t.num
return this
}
}
private fun test(){
val t = Test(1)
t + Test(2) + Test(3)
val result = t.num//结果为6
}
理解了plus的原理,还可以通过+号实现链表等
class Test(var next: Test? = null) {
operator fun plus(t: Test): Test{
next = t
return t
}
}
private fun test(){
val t = Test()
t + Test() + Test()
var sum = 1
var next = t.next
while (next != null){
sum++
next = next.next
}
}