What is the unapply method in Scala?
What is unapply
a Scala Method? How it works?
I know pattern matching in other languages ββlike OCaml and usually you have very little control over it. Is Scala unique in providing a method, unapply
or are there other languages ββthat provide a mechanism for manipulating split mapping?
source to share
unapply
Also called extractor method in Scala , 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 SomeInteger
returns None
instead SomeInteger(n)
.
Other examples of extractors can be found easily 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 the way the method is defined unapply
.
source to share