Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 969
jilen Avatar asked Dec 30 '25 11:12

jilen


1 Answers

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.

like image 155
Nicolas Avatar answered Jan 02 '26 10:01

Nicolas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!