I am new to Scala.
I have a function that accepts a string and based on different logics, I need to create a Seq of String with all permutations.
Example - input string is 00US_India0234. The result will be Seq of:
US // Condition - if string contains "US"
India // Condition - if string contains "India"
234 // Condition - if string contains number and trim
US_India // One more condition to keep countries intact and so on
Code tried so far which I didn't work
val retSeq: Seq[String] = Seq.empty
if myStr contains "US" retSeq +: "US"
I have the conditions in place but adding to Seq is not possible and I do not want to create a var.
You could create a list of tuples containing predicates and functions to process your input you want to potentially apply and append to Seq:
val numberRegex = "([0-9]{4,})".r
val predicates = List[(String => Boolean, String => String)](
(s => s.contains("US"), _ => "US"),
(s => s.contains("India"), s => s.toUpperCase()),
(s => numberRegex.findFirstIn(s).nonEmpty, s => numberRegex.findFirstIn(s).head)
)
And then you need to just create a method to build up Seq:
def process(s: String): Seq[String] = predicates.collect{
case (predicate, value) if predicate(s) => value(s)
}
process("00US_India0234") //List(US, 00US_INDIA0234, 0234)
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