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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With