Closed4

Kotlinのcompanion objectについて調べる

薄田達哉 / tatsuyasusukida薄田達哉 / tatsuyasusukida

Javaでいう所のstaticのようなものと理解しました。

サンプルコード:

object StudentProgress {
    var total: Int = 10
    var answered: Int = 3
}

class Quiz {
    companion object StudentProgress {
        var total: Int = 15
        var answered: Int = 5
    }
}

fun main() {
    println("Total = ${StudentProgress.total}, Answerd = ${StudentProgress.answered}")
    println("Total = ${Quiz.total}, Answerd = ${Quiz.answered}")
}

実行結果:

Total = 10, Answerd = 3
Total = 15, Answerd = 5
薄田達哉 / tatsuyasusukida薄田達哉 / tatsuyasusukida

companionがない場合はアクセスする時にオブジェクト名(例:StudentProgress)が必要になります。

object StudentProgress {
    var total: Int = 10
    var answered: Int = 3
}

class Quiz {
    object StudentProgress {
        var total: Int = 15
        var answered: Int = 5
    }
}

fun main() {
    println("Total = ${StudentProgress.total}, Answerd = ${StudentProgress.answered}")
    println("Total = ${Quiz.StudentProgress.total}, Answerd = ${Quiz.StudentProgress.answered}")
}

実行結果:

Total = 10, Answerd = 3
Total = 15, Answerd = 5
薄田達哉 / tatsuyasusukida薄田達哉 / tatsuyasusukida

companion objectの名前がなくても大丈夫です。

object StudentProgress {
    var total: Int = 10
    var answered: Int = 3
}

class Quiz {
    companion object {
        var total: Int = 15
        var answered: Int = 5
    }
}

fun main() {
    println("Total = ${StudentProgress.total}, Answerd = ${StudentProgress.answered}")
    println("Total = ${Quiz.total}, Answerd = ${Quiz.answered}")
}
薄田達哉 / tatsuyasusukida薄田達哉 / tatsuyasusukida

でもcompanion objectの名前があった方が拡張プロパティを追加できるのであった方がベターです。

object StudentProgress {
    var total: Int = 10
    var answered: Int = 3
}

class Quiz {
    companion object StudentProgress {
        var total: Int = 15
        var answered: Int = 5
    }
}

val Quiz.StudentProgress.progressText: String
	get() = "${answered} of ${total} answered"

fun main() {
    println(Quiz.progressText)
}

実行結果:

5 of 15 answered
このスクラップは2023/01/10にクローズされました