Home > OS >  how to assign array values to individual int variables using scala
how to assign array values to individual int variables using scala

Time:03-06

I am trying achieve the below in scala

var date="12/01/2021"
var a,b,c = date.split("/")
print(a,b,c)

//expected result 
12,01,2021

CodePudding user response:

You can write

val Array(a,b,c) = date.split("/")

or

val Array(a,b,c) = date.split("/").take(3)

However, the pattern match as @Gaël J suggested has the advantage of graceful handling of cases where the result doesn't have the 3 parts expected

CodePudding user response:

There's no way you know for sure the size of the array after splitting, which is why you cannot destructure it like this.

However you can use pattern matching:

date.split("/") match {
  case Array(a, b, c) => print(...)
  case _ => print("invalid format")
}

Or just access the array by index (not safe):

val arr = date.split("/")
val (a, b, c) = (arr(0), arr(1), arr(2))
  • Related