LoginSignup
15
14

More than 5 years have passed since last update.

【Kotlin】コンストラクタの書き方

Last updated at Posted at 2018-09-28

【経緯】

これでKotlinに四苦八苦している中で、コンストラクタで困ることが何度かあったので記載します。
先人たちがもっと詳しくて分かりやすく書いてくれているので、自分用メモ程度です。

【プライマリコンストラクタ】

クラス定義と一緒に定義されるコンストラクタ。
Kotlinではコンストラクタだと意識しないような記載になっているので、初見は「???」って感じです。
そもそも型宣言をゴリゴリ行う言語ばかりをやってきた所為で(おかげで?)、型推論を行ってくれる言語に慣れていないというのも一因なんですが。

【引数なし】

public class Book() {}

【引数あり】

public class Book(textStr:String) {
    private  var txt:String = textStr
}

【セカンダリコンストラクタ】

2つ目以降のコンストラクタ。必ずプライマリコンストラクタを呼ぶ必要があり、thisキーワードで呼び出しを行います。

【引数なし】

public class Book() {
    constructor(title:String, creator:String) : this() {}
}

【引数あり】

public class Book(title:String) {

    constructor(title:String, creator:String) : this(title) {}
}

【おまけ】

コンストラクタや初期化に関係する色々。

【初期化処理(init)を入れたい!】

public class Book(textStr:String) {
    private  var txt:String = textStr

    init {
        println(txt)
    }
}

【継承あり(コンストラクタに引数なし)】

public open class Item() {
    init {
        println("Item init!")
    }

}

public class Book(textStr:String):Item() {
    private  var txt:String = textStr
}

【継承あり(コンストラクタに引数あり)】

public open class Item(title:String) {
    var titleStr:String = title
    init {
        println("Item init!")
    }
}

public class Book(title:String):Item(title) {
    private  var str:String = title
}

【参考】

https://qiita.com/alt_yamamoto/items/f5df6434e122859f2d65
https://qiita.com/k5n/items/35e76d79ee9de4effb89#%E3%82%AF%E3%83%A9%E3%82%B9
http://www.atmarkit.co.jp/ait/articles/1804/02/news009_2.html

15
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
14