2017-02-07 7 views
2

ステートメント(printステートメントなど)とメンバーの割り当てをKotlinで混在させる方法はありますか?任意の入力のためのKotlinコンストラクタのステートメント

class MySystem { 
    ComponentA componentA; 
    ComponentB componentB; 

    public MySystem() { 
     System.out.println("Initializing components"); 
     this.componentA = new ComponentA(); 
     System.out.println("Constructed componentA"); 
     this.componentB = new ComponentB(); 
     System.out.println("Constructed componentB"); 
    } 
} 

感謝、感謝: は、ここで私は(Javaで)やりたいものの一例です。

答えて

4

はい、あります:init blocksを使用しています。 initブロックおよびプロパティ初期化子は、それらがコード内に現れるのと同じ順序で実行されている:

class MyClass { 
    init { println("Initializing components") } 

    val componentA = ComponentA() 
    init { println("Constructed componentA") } 

    val componentB = ComponentB() 
    init { println("Constructed componentA") } 
} 

あるいは、宣言および初期化分離:これは、二次のコンストラクタで動作する

class MyClass { 
    val componentA: ComponentA 
    val componentB: ComponentB 

    init { 
     println("Initializing components") 
     componentA = ComponentA() 
     println("Constructed componentA") 
     componentB = ComponentB() 
     println("Constructed componentB"); 
    } 
} 

を。

+2

ありがとうございました:私は自分でそれに答える予定はありませんでしたが、質問を書き留めたら、コードをIntelliJに貼り付けてKotlinに翻訳しました。 – f1confusion

3

は、フィールドを宣言し、初期化ブロックを使用します。

internal class MySystem { 
    val componentA: ComponentA 
    val componentB: ComponentB 

    init { 
     println("Initializing components") 
     this.componentA = ComponentA() 
     println("Constructed componentA") 
     this.componentB = ComponentB() 
     println("Constructed componentB") 
    } 
} 
関連する問題