Search code examples
scalaplaceholderfunction-literal

Questions about placeholders in Scala


Consider the following definition in Scala:

val f = ((_: Int) + 1).toString()

The code assigns to f the string representation of the function literal _ + 1, which is quite natural, except that this is not i want. i intended to define a function that accepts an int argument, increments it by 1, and returns its string format.

To disambiguate, i have to write a lambda expression with explicit parameters:

val g = (x: Int) => (x + 1).toString()

So can i conclude that the placeholder syntax is not suitable for complex function literals? Or is there some rule that states the scope of the function literal? It seems placeholders cannot be nested in parentheses(except the ones needed for defining its type) within the function literal


Solution

  • Yes, you are right in thinking that placeholder syntax is not useful beyond simple function literals.

    For what it's worth, the particular case you mentioned can be written with a conjunction of placeholder syntax and function composition.

    scala> val f = ((_: Int) + 1) andThen (_.toString)
    f: Int => java.lang.String = <function1>
    
    scala> f(34)
    res14: java.lang.String = 35