Kotlin“删除"的空参数 [英] Nullable argument for kotlin "remove"

查看:118
本文介绍了Kotlin“删除"的空参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想进一步了解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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆