https://kotlinlang.org logo
#getting-started
Title
# getting-started
p

poohbar

08/10/2022, 9:47 PM
Question about Kotlin vs Java generics: this compiles just fine in Kotlin
Copy code
open class Animal<T1, T2>

class Cat<I> : Animal<I, List<I>>()

val x: Animal<String, List<String>> = Cat()
however trying to do the same instantiation in java fails:
Copy code
Animal<String, List<String>> x = new Cat<String>() // error
Is there something I can do to improve the generics in the Kotlin code so that they can be used from Java just like from Kotlin?
e

ephemient

08/10/2022, 9:55 PM
Copy code
class Cat<I> : Animal<I, List<@JvmSuppressWildcards I>>()
p

poohbar

08/10/2022, 9:56 PM
that fixed it! thanks… just not sure why is it needed.. declaring the same 2 classes in Java works in both Java and Kotlin 🤔
e

ephemient

08/10/2022, 11:31 PM
because Kotlin's
List
is declared with an
out
type parameter, the translation to Java is normally
List<? extends String>
. this is more general than a Java
List<String>
(well, not for
String
in particular because it's
final
, but the typechecker doesn't know that)
👍 1
6 Views