Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the purpose of `val` property with `final` modifier?

Recently IntelliJ suggested to add final to one of a val properties. This particular property was initialized in init {} block. I've tried to find out what is the semantics of final val construct and when should I use it, but Kotlin is all about immutability and how val is equivalent of final in Java and so results were so noisy, that I couldn't find anything.

Example:

final val id: Int // `final` suggested by IDE

init { id = 1 }

What is the meaning and possible usages of similar property? By applying final what limitations it implies beyond immutability, which is already known? Does it have anything to do with inheritance or external access?

IntelliJ stopped sugessting final if property is private.

like image 893
wst Avatar asked Oct 25 '18 05:10

wst


People also ask

What does Val mean in Kotlin?

Whereas val is a constant variable and can not be assigned multiple times and can be Initialized only single time and is known as the immutable variable in Kotlin.

Is Val final in Kotlin?

Most Kotlin developers would agree that a val property is equivalent to a final property in Java. What if I tell you that this is not completely true and sometimes you might need a final val ? Opposite to Java, Kotlin properties are final by default unless they are explicitly marked as open!

Is final a keyword in Kotlin?

Kotlin function parameters are final. There is no val or final keyword because that's the default (and can't be changed).


1 Answers

The example as it is should not suggest adding final as it does nothing in this case. The only place where adding final makes sense in Kotlin is when overriding members. By adding final to an overridden property (or method), you're preventing subclasses from further overriding it.

For example:

open class A {
    open val x: Int = 0
}

open class B : A() {
    final override val x: Int = 25
}

class C : B() {
    override val x: Int = 56 // Error: `x` in `B` is final and cannot be overridden
}

The final keyword isn't really applicable if:

  • the class you're in isn't open,
  • the property isn't open,
  • the property is private.
like image 140
zsmb13 Avatar answered Oct 04 '22 00:10

zsmb13