https://kotlinlang.org logo
Title
j

Jay

04/19/2018, 11:33 AM
Hey guys I’m stuck with a kotlin generics problem: How to inherit from same generic interface twice with two different types?
interface A<T> {}

class B: A<Apple> {}

class MyClass: B, A<Orange> {}
Kotlin gave me an error: Type parameter T of ‘A’ has inconsistent values: Apple, Orange
d

diesieben07

04/19/2018, 11:46 AM
Simple answer: you can't.
h

hho

04/19/2018, 11:49 AM
And it's not just a Kotlin generics problem, it's a JVM generics problem due to type erasure – https://en.wikipedia.org/wiki/Generics_in_Java#Problems_with_type_erasure
l

louiscad

04/19/2018, 11:49 AM
@Jay Because of type erasure, you can only implement an interface once with the same type parameter
j

Jay

04/19/2018, 11:54 AM
got it, Thx!
m

marstran

04/19/2018, 11:55 AM
I thought you could do something like
class MyClass<T> : B, A<T> where T : Apple, T : Orange
if Apple and Orange were interfaces, but it gives an error. Anyone know what the problem is with that?
The error is
Type parameter T of 'A' has inconsistent values: Apple, T#1 (type parameter of MyClass)
. Why can't it infer that T#1 is an Apple?
p

petersommerhoff

04/20/2018, 9:09 AM
@marstran Because you want it to be an
A<Apple>
and an
A<Apple and Orange>
at the same time which is not possible due to type erasure (of course in this case it's just redundant so you can just get rid of B)