Search code examples
kotlinkotlin-delegate

In Kotlin, Why Abstract class cannot be delegated using "by" keyword just like interface


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.


Solution

  • 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.