创建新用户对象时如何避免 KotlinNullPointerException?

How to avoid KotlinNullPointerException when creating a new User object?

我在 Firebase 中有这个验证码:

auth.signInWithCredential(credential).addOnCompleteListener { task ->
    if (task.isSuccessful) {
        val firebaseUser = auth.currentUser!!
        val user = User(firebaseUser.uid, firebaseUser.displayName!!) //KotlinNullPointerException
    } 
}

这是我的用户 class:

data class User constructor(var uid: String? = null): Serializable {
    var name: String? = null

    constructor(uid: String, name: String) : this(uid) {
        this.name = name
    }
}

我在突出显示的行处得到了 KotlinNullPointerException。构造函数的调用怎么会产生这个异常呢?我怎样才能避免它?

您可以像这样在 Kotlin 中处理可为空的字段:

val user = auth.currentUser?.let { firebaseUser -> 
   firebaseUser.displayName?.let { displayName -> 
      User(firebaseUser.uid,  displayName)
   }
}

运算符!!非常危险,在大多数情况下应该避免使用

只需像这样声明您的 class:

data class User(var uid: String? = null, var name: String? = null) : Serializable

然后你可以这样称呼它:

auth.signInWithCredential(credential).addOnCompleteListener { task ->
    if (task.isSuccessful) {
        auth.currentUser?.apply {  // safe call operator, calls given block when currentUser is not null
            val user = User(uid, displayName)
        }
    } 
}

可以像这样创建用户实例:

User() // defaults to null as specified
User("id") // only id is set, name is null
User(name = "test-name") // only name is set id is null

= null 完全允许调用可选地传递参数,当不传递时默认为 null

编辑: 根据@GastónSaillén 的建议,您应该在 Android.

中使用 Parcelable
@Parcelize
data class User(var uid: String? = null, var name: String? = null) : Parcelable