`out` here restricts us from calling add ```fun <T...
# getting-started
j
out
here restricts us from calling add
Copy code
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?
Copy code
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 -
Copy code
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
s
The reason
add
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.
Its return type is affected, though, so you'll see
Any?
as the inferred type
j
for use-site
in
, is
Any?
the only thing that happens? or is there any case where it is possible to prevent method calls?
d
No way to prevent arbitrary method calls, no.
Are you just exploring the options, or are you trying to build something specific?
j
just learning, and while i understood what is explained here, it will still take some time for me to actually get it
d
Fair enough. Most of the time you won't need to explicitly use
in
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.
👍 1