0

In Kotlin, val is used to make variable/properties unchangeable, and then what is the use of final? As i know that in java final is used for restricting inheritance or to make variable constant but in kotlin val is doing the constant part then what final will do in kotlin?

ADITYA RAJ
  • 123
  • 1
  • 2
  • 8

1 Answers1

5

While val and var are used to distinguish read-only from read/write variables and properties, open and final define overridability.

Methods are final by default in Kotlin, but you can declare them open to allow subclasses to override the method. When this happens, subclasses can choose to prevent further overrides by adding the final keyword in addition to the override keyword:

open class Shape {
    open fun draw() { /*...*/ }
}
open class Rectangle() : Shape() {
    // subclasses of Rectangle can't override draw()
    final override fun draw() { /*...*/ }
}

See https://kotlinlang.org/docs/inheritance.html#overriding-methods

The same goes for defining and overriding properties too (see the next section in the docs):

open class Shape {
    open val vertexCount: Int = 0 // if this is final, we can't override it
}

class Rectangle : Shape() {
    override val vertexCount = 4
}
Joffrey
  • 32,348
  • 6
  • 68
  • 100