Abstract val
Implementing an abstract val property is not significantly different than implementing a regular val property, other than needing the override keyword as you would with implementing an abstract function:
abstract class Base {
abstract val something: String
}
class SomethingSource : Base() {
override val something: String = "like, whatever"
}
fun main() {
println(SomethingSource().something)
}
Here, Base defines an abstract property, and SomethingSource extends Base. As a result, SomethingSource needs to provide a concrete implementation of the abstract property. In this case, since it is a val, we just use a string literal.
This is equivalent to implementing a custom getter:
abstract class Base {
abstract val something: String
}
class SomethingSource : Base() {
override val something: String
get() = "like, whatever"
}
fun main() {
println(SomethingSource().something)
}
However, the get() syntax provides more flexibility. For example, suppose that we wanted to use a random number instead of a string literal. If we assign a random number to something, that is the one-and-only something value:
import kotlin.random.Random
abstract class Base {
abstract val something: Int
}
class SomethingSource : Base() {
override val something = Random.nextInt(1,100)
}
fun main() {
val source = SomethingSource()
println(source.something)
println(source.something)
println(source.something)
}
If, on the other hand, we implement get(), since get() is called on every access of the property, we get a fresh random number every time that we refer to something:
import kotlin.random.Random
abstract class Base {
abstract val something: Int
}
class SomethingSource : Base() {
override val something
get() = Random.nextInt(1,100)
}
fun main() {
val source = SomethingSource()
println(source.something)
println(source.something)
println(source.something)
}
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.