Kotlin“删除"的空参数 [英] Nullable argument for kotlin "remove"
问题描述
我只是想进一步了解Kotlin可为空的类型声明.
MutableList.remove
是:
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
但是,即使myBook
的推断类型为Stuff?
并且其值为null
,也会编译并运行以下内容.
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)
}
为什么remove
类型声明不使用可为空的T?
类型,诸如此类?
Why doesn't the remove
type declaration use the nullable T?
type, something like this?
fun <T> MutableCollection<out T>.remove(element: T?): Boolean
或更准确地说,out
修饰符如何使T
可以为空?
Or perhaps more precisely how does the out
modifier make it possible for T
to be nullable?
推荐答案
fun <T> MutableCollection<out T>.remove(element: T): Boolean
推断为Stuff?
.您的行
val found = myListOfStuff.remove(myBook)
尝试删除所有出现的null
,因为myBook
为空.它显然找不到任何东西,但编译器并不介意.
tries to remove all occurrences of null
as myBook
is null. It obviously can't find any but the compiler does not mind.
out
关键字向编译器确保不会调用像add(element)
这样的函数(add(null)
会是一个问题),只是返回像get()
这样的返回T
的函数.
The out
keyword ensures to the compiler that no functions like add(element)
will be called (add(null)
would be a problem), just functions that return T
like get()
.
请参阅以下内容进行澄清:
See this to clarify:
data class Stuff(val name: String)
fun main(args: Array<String>) {
val myListOfStuff: ArrayList<Stuff?> = arrayListOf(
Stuff("bed"),
Stuff("backpack"),
Stuff("lunch"),
null
)
println(myListOfStuff)
val found = myListOfStuff.remove(null)
println(myListOfStuff)
}
输出:
[Stuff(name=bed), Stuff(name=backpack), Stuff(name=lunch), null]
[Stuff(name=bed), Stuff(name=backpack), Stuff(name=lunch)]
对于out
关键字,请参见此处: https://kotlinlang.org/docs/reference/generics.html#declaration-site-variance
For the out
keyword see here: https://kotlinlang.org/docs/reference/generics.html#declaration-site-variance
这篇关于Kotlin“删除"的空参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!