有趣的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

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

最佳答案

在您的代码中,aabb均为MDetail?类型,但是null值本身不包含有关类型的信息,因此编译器无法为您推断类型,这是编译错误,但是如果将null转换为MDetail?,则它也会被编译:

listofMDetail.remove(null as MDetail?)

然后的问题是,当您的remove声明为listofMDetailMutableList<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值。

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

10-09 15:57