Reputation: 14285
What is unapply
method is Scala? How does it work?
I know pattern-matching in other languages such as OCaml, and usually you have very little control over it. Is Scala unique in providing unapply
method, or are there other languages that provide a mechanism for controlling patter-matching?
Upvotes: 4
Views: 1945
Reputation: 15783
In Scala unapply
is also called extractor method, for example consider this
scala> object SomeInteger {
|
| def apply(someInt: Int): Int = someInt
|
| def unapply(someInt: Int): Option[Int] = if (someInt > 100) Some(someInt) else None
| }
defined module SomeInteger
scala> val someInteger1 = SomeInteger(200)
someInteger1: Int = 200
scala> val someInteger2 = SomeInteger(0)
someInteger2: Int = 0
scala> someInteger1 match {
| case SomeInteger(n) => println(n)
| }
200
scala> someInteger2 match {
| case SomeInteger(n) => println(n)
| case _ => println("default")
| }
default
As you can see the second match prints default
because the unapply method of SomeInteger
returns a None
instead of a SomeInteger(n)
.
Other examples of extractors can easily be found for lists for example:
List(1,2,3,4) match {
case head :: tail => doSomething()
case first :: second :: tail => doSomethingElse
case Nil => endOfList()
}
This is possible because of how the unapply
method is defined.
Upvotes: 3