scala: How to convert an anonymous function to val

What you need to express is a function. So the type of the variable in this case is:

val onlyEvens: Int => Int

In particular, collect accept a PartialFunction (i.e. a function that is not defined for some input value). So it is more correct to write:

val onlyEvens: PartialFunction[Int, Int] = { case e if e % 2 == 0 => e }

Finally, you can pass this val in the collect method:

List(1,2,3,4,5).collect(onlyEvens)

Scastie


Syntax to assign an anonymous function to a val would be something like this (note parentheses around e):

   val x: Int => Int = (e) => if (e % 2 == 0) e else ??? 

or equivalently, but a bit shorter: val x = (e: Int) => if (e % 2 == 0) e else ???

But it looks like what you are looking for is a partial function rather than just a function. PartialFunction is like a regular function, but it is only defined for some of the possible values of its parameter. In your case, you want it only defined for even numbers:

    val x = PartialFunction[Int, Int] { case e if e % 2 == 0 => e }

The { case foo => bar } shorthand works for partial functions but not regular functions, that's why you were having problems trying to define a function that way. This creates a PartialFunction that is defined for all integer values that match one of the case clauses, and not for any others.