Why can only delegate interfaces be delegated to Kotlin?

I saw several similar questions, but no one explained why delegation is limited by interfaces?

In most cases, in practice, we have something that actually has no interface, it is a class that does not implement anything except to provide some functionality or implements an abstract class.

Is there any fundamental limitation that restricts this limitation to interfaces, or can we expect kotlin to have unlimited delegation in the future?

This is especially useful if we want to extend the functionality of a class using composition rather than inheritance.

class A {}
class B(val a: A) : A by a {}
+4
source share
1 answer

, . , , .

class A(x: Int) {
  fun foo() = x
}

class B(val a: A) : A by a {}

class B(val a: A) : A {
  override fun foo() = a.foo()
}

:

  • foo open .

  • A. class B(val a: A) : A(a.x) : x A.

  • equals hashCode: ? .

+4

Source: https://habr.com/ru/post/1686285/


All Articles