Why does this compile?
val regex = raw"a*".r
def matchRegex(str: String): Boolean =
str match {
case regex("abc") => true
case _ => false
}
As you can see, I don't try to extract any values from the string but instead I specify a string in the first case of the match (usually you would do something like regex(_*)
to see if it matches). The method matchRegex
always returns false
but I wonder how this doesn't throw any error not even a runtime error.
I am not sure why you would expect it to not compile. regex(<any number of strings>)
is valid syntax, and matches the extractor definition.
For example, this returns true:
val regex = "(a.*)".r
def matchRegex(str: String): Boolean = str match {
case regex("abc") => true
case _ => false
}
matchRegex("abc")
I guess, what you are really asking is why extractor does not throw a run-time error if number of parameters does not match the number of capturing groups in the regex ...
The answer to that is "that's just how it is implemented". It is not really obvious at all that throwing in this case would be a better solution than simply failing the match. Runtime errors are generally considered evil in scala (and in functional programming in general), and are only used in cases, when there is no other viable alternative.