Search code examples
scalascala-3

Scala, why can't underscore function syntax infer type?


I'm new to scala and I've stumbled upon some weird cases where type inference does not work as expected. for example, this does not compile:

List(1, 2, 3, 4, 5, 6)
    .map(if _ > 3 then "foo" else "bar")

the compiler explicitly states it can't infer the type of _$1 which I take to be the first parameter of the function the syntax above desugars to.

somewhat frustratingly, the below code compiles just fine, even with no type annotation:

List(1, 2, 3, 4, 5, 6)
    .map{ n => if n > 3 then "foo" else "bar"}

clearly there's something I'm not grasping about how _ desugars. can somebody clue me in on what's missing?


Solution

  • You are missing parenthesis:

    List(1, 2, 3, 4, 5, 6)
        .map(if (_) > 3 then "foo" else "bar")
    

    See it working for Scala 3.

    Or more "canonical" version working both for Scala 3 and Scala 2 and mentioned in Scala 2.11 spec:

    placeholder syntax. equivalent anonymous function
    _ + 1 x => x + 1
    _ * _ (x1, x2) => x1 * x2
    (_: Int) * 2 (x: Int) => (x: Int) * 2
    if (_) x else y z => if (z) x else y
    _.map(f) x => x.map(f)
    _.map( _ + 1) x => x.map(y => y + 1)
    List(1, 2, 3, 4, 5, 6)
      .map(_ > 3)
      .map(if (_) "foo" else "bar")