1

I have below use case, I know how pattern matching works in Scala but I have a requirement where I need to assign values based on the pattern, I wanted to avoid repeating code, Is there best way I can achieve this? Please let me know

sample value for test value will be a string with delimitor ','

cf match {
      case "1" => 
             val info1 => test.split(",")
             val info2 => test2.split(",")
             val info3 => test3.split(",")
             val info4 => test4.split(",")
             val info5 => test5.split(",")
      case "2" => 
             val info1 => test6.split(",")
             val info2 => test7.split(",")
             val info3 => test8.split(",")
             val info4 => test9.split(",")
             val info5 => test10.split(",")
    }

Thanks in advance

1 Answer 1

4

The best way is to do this

val cf = "1"
val test1 = "a,b,c"
val test2 = "d,e,f"
val test3 = "g,h,i"
val test4 = "j,k,l"

val (info1, info2, info3, info4, info5) = cf match {
         case "1" => (test1.split(","), test2.split(","), test1.split(","), test2.split(","), test1.split(","))
         case "2" => (test3.split(","), test4.split(","), test3.split(","), test4.split(","), test3.split(","))
  }

info1.toList.foreach{println}
info2.toList.foreach{println}
info3.toList.foreach{println}
info4.toList.foreach{println}
info5.toList.foreach{println}

this way you can reference each value individually.

Any val declaration in the pattern matching will be scoped locally to the case so technically all of those in your case will "return" unit (if those were = instead of =>)

Edit: in response to your edit. This works with any type. You can define a function that will map a tuple so you don't have to split individually

Here is a working fiddle: https://scastie.scala-lang.org/Hcpmn0OsTr6RLWkUyUFVVQ You can see it prints fine

Sign up to request clarification or add additional context in comments.

8 Comments

its throwing error saying pattern type incompatible with expected type,found Array[String] required Unit
updated the question, can you see and test it, its not working
I just tested this and it works for me. Give me a second and I will post a fiddle link
@Babu here is proof of work with integers. If you are getting type errors, it is coming from a part you didn't include or a type you didn't specify in that case please update the question accordingly scastie.scala-lang.org/MvkGMuqqRhWijZB95UHYkQ
@Babu You need to specify what does test values are and give some examples of their values. the error is coming from those values and we don't know what they are
|

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.