Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is unapply method in Scala?

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?

like image 291
Vladimir Keleshev Avatar asked Oct 28 '25 12:10

Vladimir Keleshev


1 Answers

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.

like image 109
Ende Neu Avatar answered Oct 30 '25 12:10

Ende Neu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!