Search code examples
scalafunctional-programmingcomposition

Function composition results in missing argument list for method first


Suppose we have the following functions:

def first(a: A): B = ???
def second(b: B): C = ???

I would like to compose them using andThen, but the following code:

(first andThen second)(a)

results in:

<console>:14: error: missing argument list for method first
Unapplied methods are only converted to functions when a function type is expected.
You can make this conversion explicit by writing `first _` or `first(_)` instead of `first`.                                                                                                                                                                    
(first andThen second) (1)

Solution

  • andThen() is a method on a Function. As you've defined it, first() is a method (def), not a function. Those are different entities.

    You could define it as a function...

    val first : A => B = (a:A) => ???
    

    ... or you can use eta expansion to promote it to function status.

    (first _ andThen second)
    

    Word has it that Scala 3 will offer a more transparent eta expansion mechanism so that the distinction between method and function won't be quite as cumbersome.