Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring multiple variables in Scala

Tags:

scala

I'd like to use val to declare multiple variable like this:

val a = 1, b = 2, c = 3 

But for whatever reason, it's a syntax error, so I ended up using either:

val a = 1 val b = 2 val c = 3 

or

val a = 1; val b = 2; val c = 3; 

I personally find both options overly verbose and kind of ugly.

Is there a better option?

Also, I know Scala is very well thought-out language, so why isn't the val a = 1, b = 2, c = 3 syntax allowed?

like image 314
Xavi Avatar asked Dec 30 '09 18:12

Xavi


People also ask

How do I declare a variable in Scala?

Multiple declarations can be possible in Scala using the 'var' keyword with the variable name separated by commas and the "=" sign with the value for the variable. In the above example, you can see all of the variables x,y, and z get assigned to value 5,4.5 and "Sit" correspondingly as follows.

How do I declare a global variable in Scala?

Since your run() function does not take parameters, the contents of value can also be computed without it. Show activity on this post. you can add java classes in Scala , so you can create a class and put your variables in static { } method and you can get access using private get methods .

What is difference between Val and VAR in Scala?

The difference between val and var is that val makes a variable immutable — like final in Java — and var makes a variable mutable.

What are Scala variables?

Advertisements. Variables are nothing but reserved memory locations to store values. This means that when you create a variable, you reserve some space in memory. Based on the data type of a variable, the compiler allocates memory and decides what can be stored in the reserved memory.


2 Answers

The trivial answer is to declare them as tuples:

val (a, b, c) = (1, 2, 3) 

What might be interesting here is that this is based on pattern matching. What is actually happens is that you are constructing a tuple, and then, through pattern matching, assigning values to a, b and c.

Let's consider some other pattern matching examples to explore this a bit further:

val DatePattern = """(\d{4})-(\d\d)-(\d\d)""".r val DatePattern(year, month, day) = "2009-12-30" val List(rnd1, rnd2, rnd3) = List.fill(3)(scala.util.Random.nextInt(100)) val head :: tail = List.range(1, 10)  object ToInt {   def unapply(s: String) = try {     Some(s.toInt)   } catch {     case _ => None   } }  val DatePattern(ToInt(year), ToInt(month), ToInt(day)) = "2010-01-01" 

Just as a side note, the rnd example, in particular, may be written more simply, and without illustrating pattern matching, as shown below.

val rnd1, rnd2, rnd3 = scala.util.Random.nextInt(100) 
like image 159
Daniel C. Sobral Avatar answered Sep 22 '22 12:09

Daniel C. Sobral


Daniel's answer nicely sums up the correct way to do this, as well as why it works. Since he already covered that angle, I'll attempt to answer your broader question (regarding language design)...

Wherever possible, Scala strives to avoid adding language features in favor of handling things through existing mechanisms. For example, Scala doesn't include a break statement. However, it's almost trivial to roll one of your own as a library:

case object BreakException extends RuntimeException  def break = throw BreakException  def breakable(body: =>Unit) = try {   body } catch {   case BreakException => () } 

This can be used in the following way:

breakable {   while (true) {     if (atTheEnd) {       break     }      // do something normally   } } 

(note: this is included in the standard library for Scala 2.8)

Multiple assignment syntaxes such as are allowed by languages like Ruby (e.g. x = 1, y = 2, z = 3) fall into the category of "redundant syntax". When Scala already has a feature which enables a particular pattern, it avoids adding a new feature just to handle a special case of that pattern. In this case, Scala already has pattern matching (a general feature) which can be used to handle multiple assignment (by using the tuple trick outlined in other answers). There is no need for it to handle that particular special case in a separate way.

On a slightly different aside, it's worth noting that C's (and thus, Java's) multiple assignment syntax is also a special case of another, more general feature. Consider:

int x = y = z = 1; 

This exploits the fact that assignment returns the value assigned in C-derivative languages (as well as the fact that assignment is right-associative). This is not the case in Scala. In Scala, assignment returns Unit. While this does have some annoying drawbacks, it is more theoretically valid as it emphasizes the side-effecting nature of assignment directly in its type.

like image 21
Daniel Spiewak Avatar answered Sep 20 '22 12:09

Daniel Spiewak