Do you want BuboFlash to help you learning these things? Or do you want to add or correct something? Click here to log in or create user.



#extractor-objects #scala

the following code defines an extractor object Twice. The pattern case Twice(n) will cause an invocation of Twice.unapply

object Twice {
  def apply(x: Int): Int = x * 2
  def unapply(z: Int): Option[Int] = if (z%2 == 0) Some(z/2) else None
}

object TwiceTest extends App {
  val x = Twice(21)
  x match { case Twice(n) => Console.println(n) } // prints 21
} 
If you want to change selection, open document below and click on "Move attachment"

Extractor Objects - Scala Documentation
In Scala, patterns can be defined independently of case classes. To this end, a method named unapply is defined to yield a so-called extractor. For instance, <span>the following code defines an extractor object Twice. object Twice { def apply(x: Int): Int = x * 2 def unapply(z: Int): Option[Int] = if (z%2 == 0) Some(z/2) else None } object TwiceTest extends App { val x = Twice(21) x match { case Twice(n) => Console.println(n) } // prints 21 } There are two syntactic conventions at work here: The pattern case Twice(n) will cause an invocation of Twice.unapply, which is used to match any even number; the return value of the u


Summary

statusnot read reprioritisations
last reprioritisation on suggested re-reading day
started reading on finished reading on

Details



Discussion

Do you want to join discussion? Click here to log in or create user.