【发布时间】:2020-09-28 17:50:24
【问题描述】:
我在 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。构造函数的调用怎么会产生这个异常呢?如何避免?
【问题讨论】:
-
我认为由于
name是可选变量,只需像使用 uid 一样将其放入主构造函数中,不要使用!!运算符。喜欢User(var uid: String? = null, var name: String? = null) -
@AnimeshSahu 谢谢,但我需要这种方式。
-
this way哪个方向? -
@AnimeshSahu 我需要一个带有一个参数的构造函数以及一个带有两个参数的构造函数。
-
带有可选参数的构造函数在编译时生成重载构造函数,同理。你也可以像
User("my-id")这样称呼它。
标签: android firebase kotlin firebase-authentication kotlin-null-safety