Is there any way to embed an interface in another ...
# getting-started
r
Is there any way to embed an interface in another class? Put a slightly different way, a class that inherits from an implementation of an interface. In Go, I could do something like
Copy code
type MyInterface interface {
  DoSomething() int
}

type MyObject struct {
  MyInterface
}

bar := SomeImplementationOfMyInterface()
foo := MyObject { MyInterface: bar }
foo.DoSomething() // -> calls bar.DoSomething()
The closest I can get in Kotlin seems to be manually proxying methods to the wrapped implementation:
Copy code
class MyObject(val underlying: MyInterface): MyInterface {
  override fun DoSomething() = underlying.DoSomething()
}
Which is tedious and breaks if MyInterface changes. I want to end up with an object that delegates everything to the underlying interface, but adds additional methods.
j
Kotlin has interface delegation, I guess this is what you're looking for:
Copy code
class MyObject(val underlying: MyInterface): MyInterface by underlying {
    // you may add or override methods here
}
With the
MyInterface by underlying
declaration,
MyObject
automatically implements all methods from
MyInterace
by delegating their implementation to
underlying
. You can override some of those if you want to do something different than just delegating. You can also of course add anything else as well in the body.
r
Ooh, that looks exactly what I was looking for!
Thank you!
j
My pleasure 🙂
đź’Ż 1
l
What happens if the object/interface has a “return this” in it? Is it the wrapper that’s returned, or the underlying object?
j
I haven't checked, but I believe the implementation really is exactly equivalent to delegating every method call to the underlying object, so if that object returns
this
it will be the underlying object.
l
That’s what I’d expect. And why such delegation is tricky because it becomes very leaky. 🙂