Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would one implement OCaml / F#'s "function" construct in Scala?

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?

like image 433
Electric Coffee Avatar asked Jun 28 '26 05:06

Electric Coffee


1 Answers

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.

like image 61
kiritsuku Avatar answered Jun 29 '26 21:06

kiritsuku



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!