Declare a global class variable using
companion object:
Kotlin
class MyInfo {
companion object {
var booksCount: Int = 0 // declaring a global class variable
var filmsCount: Int = 0 // declaring a global class variable
}
}
You can use
var and
val.
A global variable (called a static variable in other programming languages).
A global variable means that this variable is created in memory only 1 time when the program is started and is terminated when the program is stopped.
The global variable is available everywhere (can be used in any class)
Kotlin
class MyInfo {
companion object {
var booksCount: Int = 0 // declaring a global class variable
var filmsCount: Int = 0 // declaring a global class variable
}
}
class MyBook(bookName: String) {
init {
MyInfo.booksCount++ // use a global variable
}
}
class MyFilm(bookName: String) {
init {
MyInfo.filmsCount++ // use a global variable
}
}
fun main() {
var book1 = MyBook("The three musketeers")
var book2 = MyBook("House near lake")
var film1 = MyFilm("Matrix")
// use a global variable
println(MyInfo.booksCount) // 2
// use a global variable
println(MyInfo.filmsCount) // 1
}
На заметку!
Within
companion object, you can also use the following methods:
Kotlin
companion object {
var booksCount: Int = 0
var filmsCount: Int = 0
fun showMy() {
println("books created: $booksCount, films created: $filmsCount")
}
}