Closed4
Kotlinのcompanion objectについて調べる
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
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
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}")
}
でも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にクローズされました