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?
I guess, you are not actually calling the member function remove you refer to but rather the following extension function:
fun <T> MutableCollection<out T>.remove(element: T): Boolean
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With