Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala : how to match a case by array length

Tags:

scala

A newbie here.

We have some (possibly ugly) code that goes:

val rowSplit = line.split(",", -1)

rowSplit match {
  case array: Array[String] =>
  {
     if (array.length < 18) {
     //do sth

     }
     else if(array.length < 26){

     // smth else
     }
  }

I was wondering if we could match arrays with individual lengths directly in the case statement.

Is it possible?

PS: I donT know if this SO post answers my question. If so how?

In scala, how can I use pattern match to match a list with specified length?

like image 966
Orkun Ozen Avatar asked Jan 30 '26 12:01

Orkun Ozen


1 Answers

You can match the array and add a condition to the matching case like this :

rowSplit match {  
  case array:Array[String] if array.length < 18 => //do sth
  case array:Array[String] if array.length > 26 => ...
}

or simply:

rowSplit match {  
  case a if a.length < 18 => //do sth
  case a if a.length > 26 => ...
}

Note that here we can use variable pattern a instead of typed patterns like a:Array[String] because we don't need further type matching of rowSplit, we knew rowSplit is of type Array[String], and it has field length.

like image 64
alifirat Avatar answered Feb 01 '26 07:02

alifirat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!