LoginSignup
0
0

More than 3 years have passed since last update.

初めてkotlinを触る - クラス基礎(1)

Last updated at Posted at 2019-08-22
1 / 10

目次

  • 目的
  • クラスのコンストラクタ
  • 引数取る
  • 気になること

目的

  • javaと違うことを紹介
  • 気になることを紹介
  • kotlinの使うことを進める

コンストラクタ

  • プライマリコンストラクタ(一つ)
class Weather(state: String) {  //プライマリコンストラクタ
}
  • セカンダリコンストラクタ(複数)
class Weather(state: String) {
    constructor(state: String, temperature: Int) : this(state){ //セカンダリコンストラクタ
    }
}

コンストラクタ - コンストラクタの引数

class Weather(val state: String) {    
    init {
        println(state)
    }
}

fun main() {
    Weather("cloudy") // cloudy
}

コンストラクタ - 引数取る

class Weather(state: String) {
    val newState = state

    init {
        println(newState)
    }
}

fun main() {
    Weather("cloudy") // cloudy
}
  • プライマリコンストラクタは、どんなコードも含めない
  • 初期化コードは、initキーワードが付いている初期化ブロック内に書く

気になること1

初期化とセカンダリコンストラクタの順番?


class Weather(val state: String) {    
    init {
        println(state)
    }

    constructor(state: String, temperature: Int) : this(state){
        println("secondy constructor: " + state)
        println("temperature: " + temperature)
    }
}

fun main() {
    Weather("cloudy") // cloudy
    Weather("sunny", 30) 
    // sunny
    // secondy constructor: sunny
    // temperature: 30
}
  • 初期化ブロックはプライマリーコンストラクタ、セカンダリーコンストラクタどちらを実行した場合でも実行される
  • セカンダリーコンストラクタを実行した場合は、初期化ブロックが実行された後にセカンダリーコンストラクタの処理が実行される

気になること2

セカンダリコンストラクタの引数にvalやvarを使えないので、初期化は?

constructor(var state: String, level : String) : this(state){
// エラー: var on a second constructor paramter is not allowed


class Weather(val state: String) {
    private lateinit var newLevel : String

    init {
        println(state)
    }

    constructor(state: String, level : String) : this(state){
        println("secondy constructor: " + state)
        println("temperature: " + level)
        newLevel = level
    }

    fun getTemp() : String {
        println(newLevel)
        return newLevel
    }
}

fun main() {
    Weather("cloudy") // cloudy
    Weather("sunny", "A").getTemp()
    // sunny
    // secondy constructor: sunny
    // temperature: A
    // A
}
0
0
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
0
0