A common tendency I've discovered in Scala is something like this:
def someFunction(a: SomeClass) = a match { ... }
And from there on a is never used ever again. This pattern is SO common in FP that OCaml and F# have a built-in construct to let you ditch that parameter entirely.
Instead of writing this:
let someFunction a =
match a with
| 0 -> true
| _ -> false
you can simply write this:
let someFunction =
function
| 0 -> true
| _ -> false
So my question is, is it possible to write something like this in Scala?
def someFunction = function {
case 0 => true
case _ => false
}
Saving an otherwise unnecessary parameter.
I've attempted to write it as a function that takes a call-by-name parameter, but Scala won't let me make an empty match block.
Is it possible? Or does scala perhaps already have something like this built in?
Use a function instead of a method:
val someFunction: Int => Boolean = {
case 0 => true
case _ => false
}
You have to explicitly write the type annotations, but that must not be a drawback - for API usage it is useful documentation.
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