Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

final keyword in method  RSS feed

 
dav mrazek
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello i wonder what is the point of having a property declared final inside a method body like this (some code from a book):

Thank you for some explanation.
 
Leandro Dantas
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It avoids to someone accidentally change the object linked to this variable.

That must be used to let an anonymous class to access the object and it is a good practice.

For example:
 
Bill Shirley
Ranch Hand
Posts: 457
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The final keyword from the language specification.
 
Kelvin Chenhao Lim
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, declaring a local variable as final will make it a compile-time constant, which allows the compiler to optimize expressions involving the variable by pre-computing the result during compilation.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Kelvin Lim:
Also, declaring a local variable as final will make it a compile-time constant


Only if everything on the right-hand side is clearly constant (e.g. a literal). The compiler will employ very little "intelligence" in determining what's constant.

Originally posted by Kelvin Lim:
compile-time constant, which allows the compiler to optimize expressions involving the variable by pre-computing the result during compilation.


In theory, it does, but in practice it doesn't work very hard at this. HotSpot, on the other hand, will try real hard to optimise the code, at run-time. HotSpot will probably recognise a constant value, even if not declared final.

Overall, "final" is used mostly (a) for variables used by anonymous inner class, and (b) to make code more self-checking and self-documenting. This latter is important, but not for performance reasons.
 
Kelvin Chenhao Lim
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Peter Chase:
In theory, it does, but in practice it doesn't work very hard at this.


Ah, you're right, of course. I wasn't precise enough in my previous post; I should have also added that the final variable needs to be initialized with a compile-time constant expression. What I had in mind was the contrast between:
and
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!