Scala "const" values

val values in Scala are, by specification, const, or final in Javaspeak. That means once assigned, they cannot be re-assigned. This doesn't mean that the assignment has to be something dull or simple. In fact, you can have a large piece of code doing all sorts of calculations with the result assigned to your value. Do it like this:

  1. val result = {
  2.   val temp = callFunc() match {
  3.     case Some(x) =>
  4.     ....
  5.   }
  6.   ...
  7. }

Whatever is the value of the code block in curly brackets will be assigned as the value of result. It's that simple. Of course, such code could be moved to a function. This makes sense if it can be reused, but what's the point if it is something done only once? Of course, any valid Scala code is allowed in the code block, including function calls, values assignment and so on.

Add new comment

Subscribe to Comments for "Scala "const" values"