Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why only interfaces can be delegated to in kotlin?

I have seen few similar questions, but none had explained why delegation is limited to interfaces?

Most of the time in practice we have something that has actually no interface at all, it is a class that implements nothing but provides some functionality or implements an abstract class.

Is there any fundamental limitation that forces this to be limited to interfaces or can we expect kotlin to have unrestricted delegation in the future?

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

class A {}
class B(val a: A) : A by a {}
like image 748
vach Avatar asked Sep 24 '17 07:09

vach


People also ask

What is interface delegation Kotlin?

Advertisements. Kotlin supports “delegation” design pattern by introducing a new keyword “by”. Using this keyword or delegation methodology, Kotlin allows the derived class to access all the implemented public methods of an interface through a specific object.

What is the benefit of using interface delegation?

Interface delegation, in Kotlin, is a simple yet powerful technique that allows a class to delegate the actual implementation of the interfaces, to separate objects. NOTE: Kotlin interfaces support both abstract methods and abstract properties.

Why do we use delegation in Kotlin?

I'm an android developer and it's my pleasure to write in Kotlin because it takes my needs into account. Kotlin, unlike Java, supports delegation natively by language in the form of Class Delegation and Delegated Properties . Class Delegation feature uses Delegation pattern as an alternative to inheritance.

Why is delegation better than inheritance?

The primary advantage of delegation is run-time flexibility – the delegate can easily be changed at run-time. But unlike inheritance, delegation is not directly supported by most popular object-oriented languages, and it doesn't facilitate dynamic polymorphism.


1 Answers

When you delegate an interface, the class does still implement the interface. So for consistency, if you can delegate a class, it should work the same way. I.e.

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

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

needs to compile to

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

except this doesn't work:

  1. foo isn't open and can't be overridden.

  2. you need to call a constructor of A. class B(val a: A) : A(a.x) won't help either: x is not a member of A.

  3. What about equals and hashCode: are they delegated? Either decision would lead to weird consequences.

like image 90
Alexey Romanov Avatar answered Oct 14 '22 21:10

Alexey Romanov