问题描述
据我了解,在 Kotlin 中委派实现的想法是避免出现如下代码:
As to my understanding, the idea of delegating an implementation in Kotlin is to avoid code that looks like this:
class MyClass(val delegate : MyInterface) : MyInterface
{
override fun myAbstractFun1() = delegate.myAbstractFun1()
override fun myAbstractFun2() = delegate.myAbstractFun2()
// ...
}
相反,我们可以编写以下代码来做同样的事情:
Instead, we can write the following code which should do the same:
class MyClass(val delegate : MyInterface) : MyInterface by delegate
现在,我希望 delegate
成为可变变量,即我的代码如下所示:
Now, I'd like delegate
to be a mutable variable, i.e. my code looks like this:
var delegate : MyInterface = MyImplementation()
object MyObject : MyInterface by delegate
因此,如果我像第一个示例一样将每个抽象方法委托给 delegate
,那么更改 delegate
的值确实会改变方法的行为.但是,上面的代码编译成这个 Java 代码:
So if I'd delegated every abstract method to delegate
by myself like in the first example, changing the value of delegate
does change the behaviour of the methods. However, the above code compiles to this Java code:
public final class MyObject implements MyInterface {
public static final MyObject INSTANCE;
// $FF: synthetic field
private final MyInterface $$delegate_0 = MyObjectKt.access$getDelegate$p();
@NotNull
public String myAbstractFun1() {
return this.$$delegate_0.myAbstractFun1();
}
@NotNull
public String myAbstractFun2() {
return this.$$delegate_0.myAbstractFun2();
}
}
很明显,Kotlin 编译器决定在创建 MyObject
时将其复制到最终字段 $$delegate_0,而不是仅使用
delegate
字段code>,当我改变 delegate
So obviously, instead of just using the delegate
field, the Kotlin compiler decides to copy it when creating MyObject
to a final field $$delegate_0
, which is not modified when I change the value of delegate
有没有更好的解决方案来代替手动委派每个方法?
Is there a better solution for doing this instead of delegating every method manually?
推荐答案
可悲的是,据我所知,没有办法通过更改原始属性内容来更改委托,但您可能仍然能够通过以不可变的方式工作并复制对象来做类似的事情:
Sadly, as far as I know there is no way of changing the delegate by changing the original property content, but you might still be able to do something similar by working in an immutable way and copying the object:
interface MyInterface {
fun foo():Int
}
data class MyClass(val delegate : MyInterface) : MyInterface by delegate
object ImplementationA: MyInterface { override fun foo() = 7 }
object ImplementationB: MyInterface { override fun foo() = 5 }
val objA = MyClass(ImplementationA)
println(objA.foo()) // returns 7
val objB = objA.copy(ImplementationB)
println(objB.foo()) // returns 5
println(objA.foo()) // still 7
希望这仍然有用.
这篇关于如何将实现委托给 Kotlin 中的可变属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!