1

I came across the below placeholder syntax in scala. And could not able to under what '_' is doing in the code

def evenDef(n: Int): Int => Boolean = _ => n % 2 == 0
 //evenDef: (n: Int)Int => Boolean

val result = evenDef(2)
//res: Int => Boolean = $$Lambda$5397/911325@3aa9352

result(9)
//res18: Boolean = true

I am little confused how the above is returning 'true' for the value 9, even though its a odd number.

Can anyone help me in understand the '_' in the code ?

michid
  • 10,536
  • 3
  • 32
  • 59
RaAm
  • 1,072
  • 5
  • 22
  • 35

1 Answers1

3

The code is equivalent to

def evenDef(n: Int): Int => Boolean = (ignored: Int) => n % 2 == 0

Since ignored is not used anywhere it can be replaced with the underscore placeholder.

Admittedly the code is a bit useless the way it stands. For any integer n it returns a constant function that either returns true for even values of n and false otherwise. The argument of the returned function does not matter at all.

michid
  • 10,536
  • 3
  • 32
  • 59