提问者:小点点

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


我在Firebase中有这个认证码:

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

此我的用户类:

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

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

我在突出显示的行处得到一个KotlinNullPointerException。 构造函数的调用如何产生此异常? 我怎样才能避免呢?


共2个答案

匿名用户

只需像这样声明类:

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

匿名用户

您可以在Kotlin中处理可为空的字段,如下所示:

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

操作符!!非常危险,在大多数情况下应避免使用