0

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

3 Answers 3

2

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

Comments

1

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

Comments

0

You can pattern match directly on the date String (based on Gaël's answer)

val date = "12/01/2021"
date match {
  case s"$a/$b/$c" => print(a, b, c)
  case _ => print("invalid format")
}

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.