0

It says in Scala, pattern-matching will be converted to an invocation of unapply(...):Option[...].

Here I defined an object with unapply:

object Hello {
  def unapply(s:String): Option[String] = Some(s)
}

Then I can use it in pattern-matching:

"hello" match {
   case Hello(s) => println(s)
}

Actually(maybe) it will be converted to:

Hello.unapply("hello") match {
  case Some(s) => println(s)
  case _ =>
}

But the Some here is also a case class, so the Some.unapply will be called.

That should be infinite. Which is not possible.

So how do Scala pattern matching the Option in the underlying?

Freewind
  • 193,756
  • 157
  • 432
  • 708
  • possible duplicate of [How is pattern matching in Scala implemented at the bytecode level?](http://stackoverflow.com/questions/754166/how-is-pattern-matching-in-scala-implemented-at-the-bytecode-level) – Gabriele Petronella Jul 21 '14 at 15:55

1 Answers1

3

The result of unapply is simply not pattern-matched again. Instead, the methods isEmpty and get are called. So your example would give:

val temp = Hello.unapply("hello")
if (!temp.isEmpty) {
  val s = temp.get
  println(s)
} else {
  throw new MatchError()
}

Since 2.11, it is not even necessary to return an Option, specifically. Any class with a method isEmpty: Boolean and a method get: A will do.

sjrd
  • 21,805
  • 2
  • 61
  • 91