0

Like 'val' and 'var' in Scala.

Like 'const' and 'let' in JavaScript.

We know most of variables are immutable.

//I guarantee someone will emphasise 
//"var should be replaced with val!"
//"let should be replaced with const!"
def test(a:Int):Int={          function(a){

  var b = a                      let b = a
                          or 
  var c = 1                      let c = 1

  b + c                          return b + c
}                              }

but when I write it in Java

//someone will think it looks strange!
int test(final int a){

  final int b = a;

  final int c = 1;

  return b + c;

}

What correct way on it?

  • 1
    If you want to indicate that the variable cannot be changed, and have the compiler check it, you can mark is as final if it helps you. It is not necessary. – khelwood Oct 23 '18 at 08:13
  • 1
    Is it necessary to add `final` before immutable variables? Well of course, because they weren't immutable _variables_ without `final`. I guess what you tried to say was "immutable types", which is something different. – Tom Oct 23 '18 at 08:14
  • IMHO `final` keyword is mainly a way to indicate your intention to the compiler. Then it will warn you back if you happen to try to update this variable, and prevent you to do so. It is not **necessary**, I would rather qualify its usage as a **best practice**. – Benoit Oct 23 '18 at 08:24
  • @Benoit. But In my opinion `val` did the same thing in Scala, and recognized as a standard code. – xiang yuan Oct 23 '18 at 08:38
  • 1
    Related: [Using the “final” modifier whenever applicable in Java](https://stackoverflow.com/q/137868/1639625) – tobias_k Oct 23 '18 at 08:40
  • 1
    In the code you posted, no not necessary. Necessity is of course not the only defining factor in what is a good idea or not, or what can be considered clean code. If you think it is important: do it. But don't expect all Java developers to share your views. The final keyword can become a necessity once you start to deal with different execution scopes; lambda's and threads, most notably. [a related question](https://stackoverflow.com/questions/34865383/variable-used-in-lambda-expression-should-be-final-or-effectively-final) gives a nice overview. – Gimby Oct 23 '18 at 08:41
  • This will be end up primarily opinion based (regardless of the advantages it gives the compiler for optimizations!, because it's a pain to read and type), which is a question not very well suited to stack overflow. – Ryan Leach Oct 23 '18 at 09:17
  • Possible duplicate of [Using the "final" modifier whenever applicable in Java](https://stackoverflow.com/questions/137868/using-the-final-modifier-whenever-applicable-in-java) – Tomek Szpakowicz Oct 23 '18 at 09:45

0 Answers0