Kotlin: delegation function

I have a project that largely depends on the delegation and composition in Kotlin. Delegation of properties is a breeze, but conceptually I'm not quite sure how to achieve delegation of functions in those cases when functions depend on other composite properties. I would like to do something like this:

interface A {
  val a: String
}
class AImpl: A {
  override val a = "a"
}
interface B {
  val b: String
}
class BImpl: B {
  override val b = "b"
}

interface C<T> where T: A, T: B {
  fun c() : String
}

class CImpl<T>(val ab: T) : C<T> where T: A, T: B {
  override fun c() = ab.a + ab.b
}

// works
class ABC : A by AImpl(), B by BImpl()

// does not work
class ABC : A by AImpl(), B by BImpl(), C<ABC> by CImpl(this)

Of course, this type of thing would be achieved as follows:

interface A {
  val a: String
}
class AImpl: A {
  override val a = "a"
}
interface B {
  val b: String
}
class BImpl: B {
  override val b = "b"
}

interface C<T> where T: A, T: B {
  fun c() : String
}

class CImpl<T>(val ab: T) : C<T> where T: A, T: B {
  override fun c() = ab.a + ab.b
}

class AB : A by AImpl(), B by BImpl()

class ABC(ab: AB = AB(), c: C<AB> = CImpl<AB>(ab)) : A by ab, B by ab, C<AB> by c

but this seems awkward because it requires passing objects for composition that inflate the size of the constructors - for me it would be cleaner to initialize the objects on the site of the class itself, since they cannot be used outside the class. Is there an elegant way to do this with delegation and / or extensions?

+4
2

C extend A B . :.

interface C : A, B {
    fun c(): String
}

abstract class CImpl() : C {
    abstract override val a: String
    abstract override val b: String
    override fun c(): String = a + b
}

class ABC : A by AImpl(), B by BImpl(), CImpl()

C CImpl:

interface C : A, B {
    fun c(): String = a + b
}

class ABC : A by AImpl(), B by BImpl(), C
+2

, , issue, . (. .)

0

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


All Articles