Reputation: 16723
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
?
Upvotes: 4
Views: 243
Reputation: 61666
Starting Scala 2.13
, it's possible to pattern match a String
by unapplying a string interpolator:
"part1-part2-part3" match {
case s"$course-$subject-$topic" =>
println(s"Split tag $course, $subject, $topic")
case _ =>
println("Oops")
}
// Splitted tag part1, part2, part3
Upvotes: 5
Reputation: 31232
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
Upvotes: 7