Jason5lee
01/12/2022, 10:13 AMthis
.
class ImplByInterface2(val a: Interface2): Interface1 {...}
class MyClass : Interface1, Interace2 {
// Delegate Interface1 implementation to this
private val impl: Interface1 = ImplByInterface2(this)
}
I found it not easy to use by
. Is there any convenient way? Both language feature and IDE trick are welcomed.
Edit: makes it clearer.Joffrey
01/12/2022, 10:17 AMgetImplByMyClass
?Jason5lee
01/12/2022, 10:18 AMJason5lee
01/12/2022, 10:19 AM(AnotherInterfaceMyClassImplements) -> Interface
Joffrey
01/12/2022, 10:19 AMMyClass
to implement Interface
by delegating to the object created with getImplByMyClass
? Or do you want the impl
field of MyClass
to delegate impl.x()
calls to this
?Jason5lee
01/12/2022, 10:23 AMMyClass
to implement Interface
by delegating to the object created with getImplByMyClass.
Jason5lee
01/12/2022, 10:23 AMImplByInterface2
.Joffrey
01/12/2022, 10:27 AMMyClass
needs to be constructed before you can pass it to getImplByMyClass
- or in the edited sample, before you pass it to ImplByInteface2
. But it cannot be constructed if you can't setup the delegation, which requires the result of that call. Chicken-and-egg problem.
You'll need to break that cycle somehow, and the way to do it may depend on what your business is (so it makes sense). It's a bit hard to tell which approach would be best with this abstract example.
Can't you implement Interface2
via a separate object, and implement both interfaces by delegation in MyClass
?Michael de Kaste
01/12/2022, 10:57 AMinterface Interface1
interface Interface2 {
val x: Int
val y: Int
val z: Int
}
class Interface2Impl(
override val x: Int,
override val y: Int,
override val z: Int
) : Interface2
class MyClass private constructor(
interface2Impl: Interface2
) : Interface1, Interface2 by interface2Impl {
private constructor(
x: Int,
y: Int,
z: Int
) : this(Interface2Impl(x, y, z))
}
you can't still construct a delegation in the primary constructor, but you can create stuff in a secondary one. You could even have a
private constructor(
x: Int,
y: Int,
z: Int
) : this(
run {
your complicated code here
}
)
Joffrey
01/12/2022, 12:46 PMInterface2Impl
needing an instance of Interface1
to implement Interface2
(using your reversed naming here)Michael de Kaste
01/12/2022, 2:22 PM