Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable argument for kotlin "remove"

Tags:

kotlin

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?

like image 361
mjhm Avatar asked Mar 04 '23 02:03

mjhm


1 Answers

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
like image 90
Thorsten Schleinzer Avatar answered Apr 30 '23 14:04

Thorsten Schleinzer