Search code examples
scalacompiler-errorshigher-order-functionsparenthesesscala-placeholder-syntax

Error for parentheses in higher order function definitions (Scala)


I am facing error with round brackets in high-order definition. The following code works fine:

val foo: Int => (Int => Int) = n => n + _*2

However, after adding parentheses compiler error arises

val foo1: Int => (Int => Int) = n => n + (_*2)

Error:(34, 56) missing parameter type for expanded function ((<x$5: error>) => x$5.$times(2))

I am aware that I could use another style to avoid error:

val bar = (x: Int) => (y: Int) => x + (y*2)

I interested what is the problem with parenthesis and how to use them correctly in the same style of formatting high-order functions


Solution

  • The first case of anonymous function placeholder parameter

    val foo: Int => (Int => Int) = 
      n => n + _ * 2
    

    expands to

    val foo: Int => (Int => Int) =
      (x: Int) => (n: Int) => n + x * 2
    

    whilst the second

    val foo1: Int => (Int => Int) = 
      n => n + (_ * 2)
    

    expands to

    val foo1: Int => (Int => Int) = 
      n => n + (x => x * 2)
    

    which is a syntax error. The key is to understand the scope of underscore:

    If the underscore is inside an expression delimited by () or {}, the innermost such delimiter that contains the underscore will be used;