I'm just trying to understand a little more about Kotlin nullable type declarations.
The type declaration of MutableList.remove
is:
fun <T> MutableCollection<out T>.remove(element: T): Boolean
However the following compiles and runs even though the inferred type of myBook
is Stuff?
and its value is null
.
data class Stuff(val name: String)
fun main(args: Array<String>) {
val myListOfStuff: ArrayList<Stuff> = arrayListOf(
Stuff("bed"),
Stuff("backpack"),
Stuff("lunch")
)
val myBook = myListOfStuff.find { it.name == "book" }
val found = myListOfStuff.remove(myBook)
println(myListOfStuff)
}
Why doesn't the remove
type declaration use the nullable T?
type, something like this?
fun <T> MutableCollection<out T>.remove(element: T?): Boolean
Or perhaps more precisely how does the out
modifier make it possible for T
to be nullable?