JG
07/02/2024, 3:00 PMout
here restricts us from calling add
fun <T> test1(list: MutableList<out T>) {
list.add(list[0])
}
error (from old version of kotlin which gave better errors): Out-projected type 'MutableList<out T>' prohibits the use of 'public abstract fun add(element: E): Boolean defined in kotlin.collections.MutableList'
however, why does in
not restrict us from calling removeAt
here?
fun <T> test2(list: MutableList<in T>) {
// public fun removeAt(index: Int): E
list.removeAt(0)
}
it does work correctly when in
is used at declaration site -
class SomeList<in T> {
public fun removeAt(index: Int): T { TODO() }
}
Type parameter T is declared as 'in' but occurs in 'out' position in type T
Sam
07/02/2024, 3:37 PMadd
is prevented from being called is because you need to pass an argument, and the compiler doesn't know of any values that inhabit the correct type for that argument. The removeAt
function doesn't have any such restriction because it doesn't require any arguments of unknown type.Sam
07/02/2024, 3:39 PMAny?
as the inferred typeJG
07/02/2024, 3:48 PMin
, is Any?
the only thing that happens? or is there any case where it is possible to prevent method calls?Daniel Pitts
07/02/2024, 6:30 PMDaniel Pitts
07/02/2024, 6:30 PMJG
07/02/2024, 6:32 PMDaniel Pitts
07/02/2024, 6:34 PMin
or out
for type parameters. It's not like in Java where you might need extends
and super
in generics to make them behave the way you want.