22

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.

wst
  • 4,040
  • 4
  • 41
  • 59
  • 1
    Watch out when thinking a `val` is equivalent to Java `final`. A `val` can be implemented with a custom getter and return anything it wants. `class X { var mutable = 1; val immutableOrSoItSeems get() = mutable }` – Marko Topolnik Oct 25 '18 at 06:23

1 Answers1

28

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.
zsmb13
  • 85,752
  • 11
  • 221
  • 226
  • 1
    I've been confused because it's Springboot app with Gradle's Kotlin-Spring plugin. What it makes is, it opens bean classes for you implicitly. So the class looks closed, but is really opened. Now it makes much more sense. Thank you. :) – wst Oct 25 '18 at 06:42