简体   繁体   English

不带参数的标量

[英]scala uanpply without parameter

I am a student who studies Scala in korea. 我是一名在韩国学习Scala的学生。 I am learning about pattern matching and unapply methods. 我正在学习模式匹配和未应用的方法。 The thing I am confused about is that Emergency object has a parameter in unapply method. 我感到困惑的是, 紧急对象在未应用的方法中有一个参数。 I can't know the reason when I don't put the parameter in the match block. 我不知道为什么不将参数放入match块中的原因。

object Solution {

  def main(args: Array[String]) {

    val number1 = "010-123-1234"
    val number2 = "119"
    val number3 = "포도먹은 돼지"
    val numberList = List(number1, number2, number3)

    for (number <- numberList) {
      number match {
        case Emergency() => println("긴급전화다")
        case Normal(number) => println("일반 전화다" + number)
        case _ => println("판단할 수 없습니다.")
      }
    }
  }
}

object Emergency {
  def unapply(number: String): Boolean = {
    if (number.length == 3 && number.forall(_.isDigit)) true
    else false
  }
}

object Normal {
  def unapply(number: String): Option[Int] = {
    try {
      Some(number.replaceAll("-", "").toInt)
    } catch {
      case _: Throwable => None
    }
  }
}

Notice that return types of to unapply methods are different. 请注意, unapply方法的返回类型是不同的。

Normal.unapply returns an Option . Normal.unapply返回一个Option When you do case Normal(foo) , unapply is called, and, if it returns Some(number) , the match is successful, and the number is assigned to local variable foo , and if it returns None , match fails. 当执行case Normal(foo) ,将调用unapply ,并且如果它返回Some(number) ,则匹配成功,并且将该number分配给局部变量foo ,如果返回None ,则匹配失败。

Emergency.unapply returns a Boolean , so case Emergency() succeeds if it returns true , and fails otherwise, but there is no result to assign in case of success, thus, no "parameter". Emergency.unapply返回一个Boolean ,因此case Emergency()如果返回true成功,否则返回失败,但是如果成功则没有结果可分配,因此没有“参数”。

The parameter in unapply is the object on which you are matching. unapply中的参数是您要匹配的对象。

In this case the number String variable is passed to Emergency.unapply , Normal.unapply etc. 在这种情况下, number String变量将传递给Emergency.unapplyNormal.unapply等。

This link explains things nicely: 该链接很好地解释了事情:

https://danielwestheide.com/blog/2012/11/21/the-neophytes-guide-to-scala-part-1-extractors.html https://danielwestheide.com/blog/2012/11/21/the-neophytes-guide-to-scala-part-1-extractors.html

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

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