9

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.

2 Answers 2

23

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
Sign up to request clarification or add additional context in comments.

4 Comments

nice, but it seems to produce matcherror if the list doesn't have size 3.
@SebastienLorber val List(hours, minutes, seconds, _*)
@om-nom-nom that's right but it only works when size > 3 no? I think it works fine but can be dangerous to use in some situations
@SebastienLorber no it should be fine in case of 3 values: val List(hours, minutes, seconds, _*) = List(1,2,3) will compile and execute effortlessly. It will only fail in case of less than 3 which is pretty desired behaviour.
4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.