有趣的findLast
将返回MDetail?
,因此var aa
的值可能为null。
有趣的remove
接受一个非null参数,但是为什么可以编译代码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
...........
}
最佳答案
在您的代码中,aa
和bb
均为MDetail?
类型,但是null
值本身不包含有关类型的信息,因此编译器无法为您推断类型,这是编译错误,但是如果将null
转换为MDetail?
,则它也会被编译:
listofMDetail.remove(null as MDetail?)
然后的问题是,当您的
remove
声明为listofMDetail
且MutableList<MDetail>
后没有?
时,为什么MDetail
可以工作。这是因为
remove
方法没有解析为public interface MutableList<E>
,而是MutableCollections.kt
的remove
,这是代码: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?
,而MDetail
为out T
,因此remove
将接收类型为MDetail?
的参数,该参数允许null
值。关于android - 为什么我可以在Kotlin中将null参数传递给需要非null的乐趣?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51412675/