Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to initialize multiple variables from array or List in Scala?

Tags:

scala

What I want to do is basically the following in Java code:

String[] tempStrs = generateStrings();
final int hour = Integer.parseInt(tempStrs[0]);
final int minute = Integer.parseInt(tempStrs[1]);
final int second = Integer.parseInt(tempStrs[2]);

However, tempStrs is just a temporary variable, which is not used anymore. Then, this can be expressed in the following code in F#:

let [| hour; minute; second |] = Array.map (fun x -> Int32.Parse(x)) (generateStrings())

Is there a similar way to do this in Scala? I know this can be done in Scala by

val tempInts = generateStrings().map(_.toInt)
val hour = tempInts(0)
val minute = tempInts(1)
val second = tempInts(2)

But is there a shorter way like F# (without temp variable)?


Edit:

I used

var Array(hour, minute, second) = generateStrings().map(_.toInt)

Of course, using val instead of var also worked.

like image 755
Naetmul Avatar asked Aug 19 '13 06:08

Naetmul


People also ask

How to initialize multiple variables in Scala?

The multiple assignments can be possible in Scala in one line by using 'val' keyword with 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 a,b, and c get assigned to value 1 as follows.

How do I assign a variable to a list in Scala?

Syntax for defining a Scala List. val variable_name: List[type] = List(item1, item2, item3) or val variable_name = List(item1, item2, item3) A list in Scala is mostly like a Scala array. However, the Scala List is immutable and represents a linked list data structure.

How to create variable of a function in Scala?

Syntax. var myVar = 10; val myVal = "Hello, Scala!"; Here, by default, myVar will be Int type and myVal will become String type variable.


2 Answers

How about this:

scala> val numbers = List(1, 2, 3)
numbers: List[Int] = List(1, 2, 3)

scala> val List(hours, minutes, seconds) = numbers
hours: Int = 1
minutes: Int = 2
seconds: Int = 3
like image 111
sberry Avatar answered Nov 04 '22 03:11

sberry


To deal with three or more values, you could use:

scala> val numbers = List(1, 2, 3, 4)
numbers: List[Int] = List(1, 2, 3, 4)

scala> val num1 :: num2 :: num3 :: theRest = numbers
num1: Int = 1
num2: Int = 2
num3: Int = 3
theRest: List[Int] = List(4)

For a size-3 list theRest will simply be the empty list. Of course, it doesn't handle lists of two or fewer elements.

like image 33
Shadowlands Avatar answered Nov 04 '22 01:11

Shadowlands