In my code, a string is expected to have the following structure part1-part2-part3
. The different parts are separated by -
and there can only be 3 parts.
So far I have used split
method of String
and can check the length of the returned Array
to validate the structure:
val tagDetails: Array[String] = tag.split('-') //syntax of received tag is part1-part2-part3
if (tagDetails.length == 3) {
val course: String = tagDetails(0)
val subject: String = tagDetails(1)
val topic: String = tagDetails(2)
println("splitted tag " + course + ", " + subject + ", " + topic)
} else {..}
How can I do the same using match
?
You can destructure the Array of splitted values with match
.
val tag = "course-subject-topic"
tag.split('-') match {
case Array(course, subject, topic) =>
println("splitted tag " + course + ", " + subject + ", " + topic)
case _ => println("Oops")
}
pattern match can also have if
guard as below,
tag.split('-') match {
case Array(course, subject, topic) if course != subject =>
println("splitted tag " + course + ", " + subject + ", " + topic)
case _ => println("Oops")
}
Reference - https://docs.scala-lang.org/tour/pattern-matching.html
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