How can I delegate an implementation to a mutable property in Kotlin?

前端 未结 1 545
甜味超标
甜味超标 2020-12-19 06:30

As to my understanding, the idea of delegating an implementation in Kotlin is to avoid code that looks like this:

         


        
1条回答
  •  有刺的猬
    2020-12-19 07:17

    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
    

    Hope this is still useful.

    0 讨论(0)
提交回复
热议问题