Nullable类型仍然在Kotlin抛出nullpointer异常

ksg*_*rkn 0 nullpointerexception null-pointer kotlin

下面的代码在第三行中抛出nullpointer异常.因为objectHashMap为null.但这怎么可能呢.它是一个可以为空的类型,它可以为null.

val objectsGTypeInd = object : GenericTypeIndicator<HashMap<String, Post>>() {}
val objectHashMap: HashMap<String, Post>? = dataSnapshot?.getValue(objectsGTypeInd)
val postList = ArrayList<Post>(objectHashMap?.values)
Run Code Online (Sandbox Code Playgroud)

在logcat上写的"collection == null"消息

Tod*_*odd 5

当你打电话时ArrayList<Post>(null),你会遇到这个问题.如果您objectHashMap为null,或者它不包含任何值,那么您将为null.编译器并没有真正抱怨你有一个null,它抱怨你将它传递给ArrayList()构造函数.

如果您查看JavaDoc ArrayList,它表明该集合不能为null,或者您将获得NullPointerException:

/**
 * Constructs a list containing the elements of the specified
 * collection, in the order they are returned by the collection's
 * iterator.
 *
 * @param c the collection whose elements are to be placed into this list
 * @throws NullPointerException if the specified collection is null
 */
Run Code Online (Sandbox Code Playgroud)