简体   繁体   English

如何在基础中对`Option`进行模式匹配?

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

It says in Scala, pattern-matching will be converted to an invocation of unapply(...):Option[...] . 它说在Scala中,模式匹配将转换为对unapply(...):Option[...]的调用。

Here I defined an object with unapply : 在这里,我定义了一个对象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. 但是Some这里也是case class ,因此Some.unapply将被调用。

That should be infinite. 那应该是无限的。 Which is not possible. 这是不可能的。

So how do Scala pattern matching the Option in the underlying? 那么Scala模式如何匹配底层的Option

The result of unapply is simply not pattern-matched again. unapply的结果根本不会再次进行模式匹配。 Instead, the methods isEmpty and get are called. 而是调用方法isEmptyget 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. 从2.11开始,甚至没有必要专门返回Option Any class with a method isEmpty: Boolean and a method get: A will do. 任何具有isEmpty: Boolean方法和get: A方法get: A都可以。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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