Lets say I want to write the following function using Scala's pattern matching:
def foo(num: Int): Int = {
num match {
case 1 => 0
case x if x%2 == 0 => 1
case _ => _
}
}
But of course I get a compilation error for the line case _ => _
I know I can solve it by changing the line to be something like: case x=>x, but why Scala's pattern matching doesn't allow me to do something like that? It's like a way for me saying I don't care what's there just return it.
Because it doesn't really make sense. case _ means "match anything and don't assign the value to a symbol", but what should => _ mean? If you don't care what it is, does that mean the compiler can just put in a random value?
case x => x will eagerly match everything and return the same value. It's clear, concise, and the same amount of characters as what you want. Anyone who reads it can understand what is happening. You could literally translate it as "I don't care what's there, just match it and return it".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With