Scala Tutorial
Basics
Control Statements
OOP Concepts
Parameterized - Type
Exceptions
Scala Annotation
Methods
String
Scala Packages
Scala Trait
Collections
Scala Options
Miscellaneous Topics
In Scala, the unapply
and unapplySeq
methods are used for pattern matching. While unapply
is commonly used for extracting values from instances of classes (often in the context of case classes), unapplySeq
is designed to match and extract values from sequences.
The unapplySeq
method can be used when you want to pattern match on a sequence of elements without knowing the exact number of elements beforehand. The typical return type for unapplySeq
is Option[Seq[T]]
, where T
is the type of the elements.
Let's consider a basic example where we want to match against a String
and extract its individual characters:
object StringExtractor { def unapplySeq(str: String): Option[Seq[Char]] = Some(str) } val sample = "Hello" sample match { case StringExtractor(a, b, c, d, e) => println(s"Matched: $a, $b, $c, $d, $e") case _ => println("Not matched") }
In the example above, we defined an unapplySeq
method in the StringExtractor
object that returns the characters of a given string. Then, we pattern matched the string "Hello"
against the extractor, and it matched successfully, printing the characters.
Using unapplySeq
, you can also match sequences of variable lengths:
val sample2 = "Hi" sample2 match { case StringExtractor(a, b) => println(s"Matched: $a, $b") case StringExtractor(a, b, c, _*) => println(s"Matched at least 3 chars: $a, $b, $c") case _ => println("Not matched") }
In the above example, the second case could also match sequences with more than three characters due to the use of the vararg pattern _*
.
The unapplySeq
method in Scala provides a flexible way to destructure sequences in pattern matching. It can be particularly useful when working with sequences of unknown lengths. By defining custom unapplySeq
methods, you can tailor pattern matching to suit the specific needs of your application.