开发者

Scala alternative cases match syntax with different type of extracted value

开发者 https://www.devze.com 2023-03-29 13:20 出处:网络
object NoSense { def main(args: Array[String]) { val value = \"true\" match { case value @ (IntValue(_) | BooleanValue(_)) => value
object NoSense {
   def main(args: Array[String]) {
      val value = "true" match {
         case value @ (IntValue(_) | BooleanValue(_)) => value
      }
      require(value == true)
   }
}

class Value[T](val regex: Regex, convent: String => T) {
   def unapply(value: String): Option[T] = value match {
      case regex(value, _*) => Some(convent(value))
      case _ => None
   }
}
object IntValue extends Value[Int]("[0-9]+".r, _.toInt)
object BooleanValue extends Value[Boolean]("((true)|(false))".r, _.toBoolean)

The require in the main method will fail.

but this one is ok

def main(args: Array[String]) {
      val value = "true" match {
         case IntValue(value) => value
         case BooleanValue(value) => value
      }
    开发者_Python百科  require(value == true)
   }

Is that the limitation of scala language itself or i am doing in a wrong way


It's... both.

You may take a look how at how the pattern binder behave in the Scala specification §8.1.3. It says that in pattern x@p:

The type of the variable x is the static type T of the pattern p.

In your case, the pattern p is IntValue(_) | BooleanValue(_). As IntValue and BooleanValue unapply-methods both require a String, the static type of your pattern is String, thus, the type of xis String.

In the second case, value is extracted from BooleanValue and have the right type.

Unfortunately, scala does not support alternatives of extractors patterns, thus you must stick to your second version.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号