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
}
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:In your case, the pattern
pisIntValue(_) | BooleanValue(_). AsIntValueandBooleanValueunapply-methods both require a String, the static type of your pattern isString, thus, the type ofxisString.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.