簡體   English   中英

Kotlin主要構造函數調用次要構造函數

[英]Kotlin primary constructor calling secondary constructor

為什么不編譯?

class test
{
  constructor() {
      var a = Date().day
      this(a)
  }

  constructor(a:Int) {
  }
}

錯誤是:無法將類型為“ test”的表達式“ this”作為函數調用。 找不到函數“ invoke()”。

建議的解決方案是添加以下內容:

private operator fun invoke(i: Int) {}

為什么?

首先,這兩個構造函數都是輔助構造函數。 主要構造函數是位於類主體外部的構造函數。

其次,如文檔中所述,調用另一個構造函數的正確語法如下:

class Test {
    constructor() : this(1) { }

    constructor(a: Int) { }
}
class test constructor(){ // primary constructor (The primary constructor is part of the class header: it goes after the class name (and optional type parameters))

    constructor(a: Int) : this() { // secondary constructor

    }
}

如果您的類具有定義的primary constructor ,則secondary constructor需要委托給primary constructor 這里

我認為不能secondary constructor調用primary constructor secondary constructor

您可以這樣想:次要呼叫主要和次要呼叫次要=>無限循環=>不可能

在您的情況下,有2個secondary constructor ,因此您可以像

class test {

    constructor() : this(Date().day) // I see it quite like Java here https://stackoverflow.com/questions/1168345/why-do-this-and-super-have-to-be-the-first-statement-in-a-constructor

    constructor(a: Int) {
    }
}

這里有幾處錯誤:

  • 類的名稱應始終使用駝峰式大小寫( test > Test
  • 您不能像嘗試那樣調用其他構造函數this(1)在其他構造函數主體內部調用this(1)

我想你真正想要的是a是一個屬性,或者用默認值初始化。 你可以這樣

class Test(val a: Int) {
    constructor() : this(1) // notice how you can omit an empty body
}

甚至更好,像這樣:

class Test(val a: Int = 1) // again an empty body can be omitted.

編輯:

如果您需要進行一些計算,請按照Yole答案下方的評論中的要求進行:

class Test(val day: Int) {
    // you can use any expression for initialization
    constructor(millis: Long) : this(Date(millis).day) 
}

或者事情變得更加復雜:

class Test(var day: Int) {
    // pass something (i.e. 1) to the primary constructor and set it properly in the body
    constructor(millis: Long) : this(1) { 
        // some code
        day = // initialize day
    }
}

暫無
暫無

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

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