Why can't I use `by` delegation for an interface w...
# getting-started
d
Why can't I use
by
delegation for an interface with two different type parameters? Is there some kind of workaround to this?
Copy code
interface Foo<T> { ... }

class Bar(val foo1: Foo<Baz>, val Foo<Baz2>): Foo<Baz> by foo1, Foo<Baz2> by foo2
g
Because you can't inherit the same interface several times with different (precisely, "inconsistent") type arguments. For example, the following won't be compiled as well.
Copy code
interface Foo<T>

interface Baz
interface Baz2

class Bar: Foo<Baz>, Foo<Baz2>
d
Oh... it's funny that Kotlin's type inference wouldn't know the difference... the implementations are totally different...
v
That's called type erasure. At runtime it would be just
class Bar: Foo<*>, Foo<*>
and where you used
T
,
Any
.
d
I thought that was when retrieving from, say, a collection, since the type in the collection is the base type, and the elements could be any type derived from them... but foo1 and foo2 are:
Copy code
class Foo1 : Foo<Baz> { override fun Baz.build(...): Baz ... }
class Foo2 : Foo<Baz2> { override fun Baz2.build(...): Baz2 ... }
Maybe I need some
in
or
out
there?
a
Copy code
class Bar(val foo1: Foo1, val foo2: Foo2) : Foo<Baz1> by foo1, Foo<Baz2> by foo2

fun test(foo: Foo<*>) {
    foo.baz()
}

val thing: Bar = createBar()
test(thing)
How would
test
choose between calling
baz
on foo1 or foo2?
👍🏼 1