https://kotlinlang.org logo
Title
s

svenjacobs

08/15/2022, 12:59 PM
Hello, I would like to implement the class delegation pattern by delegating to a property which is initialized during class initialization. I think technically this should work but Kotlin 1.7.10 doesn’t accept this construct. The reason why I want to delegate to a property is because when I create an instance of the delegate, I need to access an extension value which is declared in a third-party library. Is there an alternative besides having to implement the delegation manually? Is this something that a future version of Kotlin might support?
class Derived(
    factory: (dep: Dependency) -> Base,
) : SomeBaseClass(), Base by delegate {

    private val delegate = factory(dependency)
}

val SomeBaseClass.dependency: Dependency
  get() = ...
m

mkrussel

08/15/2022, 1:03 PM
Unfortunately this does not work. Not sure why, but I’m guessing the interface delegation happens before property initialization. The way I’ve worked around this is to create a private primary constructor that takes the
delegate
and then have the secondary public constructor create it and pass it to the primary.
s

svenjacobs

08/15/2022, 1:15 PM
Unfortunately when using a secondary constructor Kotlin gives me
Cannot access 'dependency' before superclass constructor has been called
class Derived(
  delegate: Base
): SomeBaseClass(), Base by delegate {

  constructor(
    factory: (Dependency) -> Base
  ) : this(factory(dependency))
                   ~~~~~~~~~~
}
m

mkrussel

08/15/2022, 1:24 PM
Yeah, in this case I don’t think you have a way to do this.
s

svenjacobs

08/15/2022, 1:26 PM
I hope this will be possible in a future version of Kotlin 🤞🏼
I created a feature request at YouTrack.