gpt4 book ai didi

android - 为什么我可以将 null 参数传递给在 Kotlin 中需要非 null 的函数?

转载 作者:搜寻专家 更新时间:2023-11-01 07:43:02 27 4
gpt4 key购买 nike

有趣的 findLast 将返回 MDetail? ,因此 var aa 的值可能为空。

有趣的remove接受一个非空参数,但是为什么代码listofMDetail.remove(aa)可以被编译?谢谢!

更重要的是,代码A可以正常运行!

代码A

private val listofMDetail:MutableList<MDetail> = myGson.fromJson<MutableList<MDetail>>(mJson)

fun deleteDetailByID(_id:Long){
var aa=listofMDetail.findLast { it._id == _id };

//listofMDetail.remove(null) //It doesn't work
listofMDetail.remove(aa) // It can be compiled

var bb: MDetail?=null
listofMDetail.remove(bb) // It can be compiled

}

源代码

public interface MutableList<E> : List<E>, MutableCollection<E> {
// Modification Operations
override fun add(element: E): Boolean

override fun remove(element: E): Boolean

...........
}

最佳答案

在您的代码中,aabb两者都是 MDetail? 类型,但是 null value 本身不包含有关类型的信息,因此编译器无法为您推断类型,这是一个编译错误,但如果您转换 nullMDetail? ,那么它也会被编译:

listofMDetail.remove(null as MDetail?)

那么问题来了,为什么remove当你的 listofMDetail 工作时声明为 MutableList<MDetail>没有?MDetail 之后.

那是因为 remove方法未解析为 public interface MutableList<E> ,但是MutableCollections.ktremove ,这里是代码:

package kotlin.collections

/**
* Removes a single instance of the specified element from this
* collection, if it is present.
*
* Allows to overcome type-safety restriction of `remove` that requires to pass an element of type `E`.
*
* @return `true` if the element has been successfully removed; `false` if it was not present in the collection.
*/
@kotlin.internal.InlineOnly
public inline fun <@kotlin.internal.OnlyInputTypes T> MutableCollection<out T>.remove(element: T): Boolean
= @Suppress("UNCHECKED_CAST") (this as MutableCollection<T>).remove(element)

在您的例子中,通用类型 T 是 MDetail? , 和 MDetailout T , 所以 remove将接收类型为 MDetail? 的参数, 这允许 null值(value)。

关于android - 为什么我可以将 null 参数传递给在 Kotlin 中需要非 null 的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51412675/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com