Why delegation always forward to the initial value

I came across that when I was trying to implement the Strategy Pattern in Head First Design Pattern.

Therefore, the following code does not work.


    val rubberDuck: RubberDuck = RubberDuck(FlyNoWay(), Squeak())
    rubberDuck.display()
    rubberDuck.fly()
    rubberDuck.quack()
    println("=================================================")

    println()
    makeRubberFlyable(rubberDuck)
}

fun makeRubberFlyable(rubberDuck: RubberDuck) {

    println("Make Rubber Duck Flyable!")

    rubberDuck.flyBehavior = FlyWithRocket()
    rubberDuck.fly()
}

Is there any reason to always forward to the initial value instead of forwarding to the content of var?

Thanks.

That’s how the delegation works right now: it copies the reference to the delegate upon creation, and delegates all calls to that reference.

The reason why it doesn’t work another way is simple: it just wasn’t designed/implemented/tested/documented by somebody.

There is a couple of feature requests to make it possible to switch a delegate during lifetime of an object: