简体   繁体   中英

How to pattern-match an `Option` in the underlying?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM