Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala pattern matching default

Tags:

scala

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.

like image 901
guymaor86 Avatar asked Jun 29 '26 21:06

guymaor86


1 Answers

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

like image 96
Michael Zajac Avatar answered Jul 02 '26 12:07

Michael Zajac