Scala alternative cases match syntax with different type of extracted 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.
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 x
is 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.
精彩评论