简体   繁体   中英

scala uanpply without parameter

I am a student who studies Scala in korea. 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.

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.

Normal.unapply returns an 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.

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".

The parameter in unapply is the object on which you are matching.

In this case the number String variable is passed to Emergency.unapply , Normal.unapply etc.

This link explains things nicely:

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

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