2
interface IA {
    fun callMe()
}

abstract class AbstractA {
    abstract fun callMe()
}

// Allowed
class ImplementationA(a: IA): IA by a

//Why this is Not Allowed ?
class ImplementationA(a: AbstractA): AbstractA() by a

I could not find any satisfactory reason on why Abstract class cannot be delegated using "by" keyword.

Note: Saying that we need to call constructor of Abstract class while extending it , this is not a satisfactory technical answer for the problem.

Pankaj
  • 1,242
  • 1
  • 9
  • 21
  • 3
    Does this answer your question? [Why only interfaces can be delegated to in kotlin?](https://stackoverflow.com/questions/46387525/why-only-interfaces-can-be-delegated-to-in-kotlin) – Cililing May 10 '21 at 08:25
  • 1. No, those statements in accepted answer are not satisfactory enough. Before providing link, did you yourself found that answer satisfactory ? If yes, can you explain what is the problem in delegating Abstract class ? ---- 2. They are not even talking about Abstract class in that Answer. – Pankaj May 10 '21 at 08:33
  • 1
    I actually agree with @Cililing and found the answer satisfactory. Which part do you find doesn't apply? It outlines why only interfaces can be used and as an abstract class isn't an interface then it answers your question perfectly? – Henry Twist May 10 '21 at 09:31
  • 1
    Yes, I checked the answer, and your question is perfectly addressed by that answer. So, simply answering your question - you cannot use an abstract class as a delegate because it's not an interface. In the linked question, however, there is an explanation why delegating is limited to interface exclusively. – Cililing May 10 '21 at 09:36

1 Answers1

2

It's impossible because delegating is limited to interfaces exclusively.

One of the main reasons is, let's say, breaking the contract - if a class is delegated, what with "default" methods, like toString, hashCode, equals - should they be delegated or not?

This question (Why only interfaces can be delegated to in Kotlin) explains why it that and what would be consequences of dropping this limitation.

Cililing
  • 4,303
  • 1
  • 17
  • 35