我是Kotlin的新手,我不知道如何解释这个,但这个例子应该足够了
interface Walker{
var position:Pair<Int,Int>
fun walk(to:Pair<Int,Int>){
position = to;
}
fun trip()
}
class People(override var position: Pair<Int, Int>):Walker{
override fun trip() {
Log.v("TP","Ouch!!")
}
}
class Superman(override var position: Pair<Int, Int>): Walker by People(position){
}
当我打电话
val sm = Superman(Pair(0,0))
sm.walk(Pair(2,2))
Log.v("TP","${sm.position}" //It give (0,0) instead of (2,2)
是否有可能在使用委托
的同时修复此问题答案 0 :(得分:0)
更改
class Superman(override var position: Pair<Int, Int>): Walker by People(position)
到
class Superman(position: Pair<Int, Int>): Walker by People(position)
这样您只需将position
的初始值传递给代理,而不是再次覆盖position
,这将取代最初委派给Person
的实现。