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)?
I used
var Array(hour, minute, second) = generateStrings().map(_.toInt)
Of course, using val
instead of var
also worked.
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.
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.
Syntax. var myVar = 10; val myVal = "Hello, Scala!"; Here, by default, myVar will be Int type and myVal will become String type variable.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With