Why case 2 causes "unbound placeholder parameter" while case 1 is OK?
val h: (Int => Int) = (x:Int) => { scala.util.Random.nextInt(x) }
val _h: (Int => Int) = { scala.util.Random.nextInt(_) }
h(5) // 3
_h(5) // 3
val f: (Int => Int) = (x:Int) => { x }
f(5) // 5
// Causes error
val _f: (Int => Int) = { _ } <----- unbound placeholder parameter
.nextInt(_)
is not an example of placeholder usage. In this case the underscore _
is used for "eta expansion" of the nextInt()
method, i.e. promoting the method to a proper function. The result is equivalent to the following:
val _h: (Int => Int) = util.Random.nextInt
To get your _f()
code to work you could do this.
val _f: (Int => Int) = identity