Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between val and final in kotlin?

Tags:

java

kotlin

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?

like image 804
ADITYA RAJ Avatar asked Nov 02 '25 11:11

ADITYA RAJ


1 Answers

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
}
like image 147
Joffrey Avatar answered Nov 04 '25 00:11

Joffrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!