簡體   English   中英

Android Kotlin-二級構造函數

[英]Android kotlin - secondary constructor

我想用兩個構造函數實現一個類。 空的構造函數和另一個具有參數user:FirebaseUser

但是我收到消息錯誤:

“代表團變更有一個周期”

class UserModel(user: FirebaseUser) {

    var uid: String?
    val email: String?
    val phoneNumber: String?
    val photoUrl: String
    val displayName: String?

    //error message: There is a cycle in the delegation change
    constructor():this() {}


    init {
        this.displayName = user.displayName
        this.email = user.email
        this.phoneNumber = user.phoneNumber
        this.photoUrl = user.photoUrl!!.toString()
        this.uid = user.uid
    }



    companion object {

        @Exclude
        val CURRENT_LOCATION = "location"
    }

}

我嘗試了幾種方法但均未成功。 有什么幫助嗎?

所有輔助構造函數都必須直接或間接調用主構造函數。 意思是:

class X(var x: Int){
    constructor() : this(0.0);
    constructor(x: Double) : this(x.toInt());
}

但是,您不能這樣做:

class X(var x: Int){
    constructor() : this();
    constructor(x: Double) : this();
}

因為這會導致堆棧溢出異常。

上面的示例是可怕的代碼,但這只是一個演示。

所以這行:

constructor():this() {}

您可以使輔助構造函數自行調用。

而是調用主構造函數。 這意味着您需要傳遞FirebaseUser作為參數。 我對Firebase並不熟悉,所以我將其留給您。

但是作為示例,您基本上需要這樣做:

constructor() : this(FirebaseUser());

直接初始化,或從方法中獲取它。 如果您無法獲得一個,則當然可以將其設置為可為空。

但是,如果您要處理可空值,那么假設您的大多數代碼都在Kotlin中,則可以使用默認值將其設置為可空值,然后刪除輔助構造函數:

class UserModel(user: FirebaseUser? = null){
    init{
        // Now that `user` is nullable, you need to change the assignments to include null-safe or non-null assertion (?. or !!. respectively)
    }
}

您必須從擁有的每個輔助構造函數中調用主構造函數,因為它的參數可能在屬性初始化程序和初始化程序塊中使用,就像您在代碼的init塊中使用過user一樣。

使用此代碼,輔助構造函數只是遞歸地調用自身:

constructor() : this() {}

相反,您應該做的是調用主構造函數,以便可以初始化類的屬性:

constructor() : this(FirebaseUser()) {} // get FirebaseUser from somewhere

另外,如果您要執行的操作是在調用第二個無參數構造函數時將所有內容保留為null ,則可以選擇以下內容:

class UserModel(user: FirebaseUser?) {

    var uid: String? = user?.uid
    val email: String? = user?.email
    val phoneNumber: String? = user?.phoneNumber
    val photoUrl: String? = user?.photoUrl?.toString()
    val displayName: String? = user?.displayName

    constructor() : this(null)

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM