For yes functions, but not for methods. Your problem is that you are trying to use a method for g , not a function. For functions, there is already a method for doing this, called andThen :
val f: Int => Int = _ + 1 val g: Int => String = _.toString scala> val fg = f andThen g fg: Int => String = <function1> scala> fg(2) res3: String = 3
Your own implicit class will work (although I didnโt look at the exact semantics you want) using functions like f and g as I defined them. It will work even for function and method (in that order).
def a(i: Int): Int = i + 1 def b(i: Int): String = i.toString scala> f andThen a res4: Int => Int = <function1>
However, a andThen b does not work as-is, because a is a method that you cannot call andThen on. To use andThen , a must be converted to a function that will not be executed automatically because the function is not necessarily expected. a _ andThen b eta-expand a into a function that has a method called andThen , and it can be given the argument b (method), because the compiler will implicitly convert b to a function, because the function is the only thing expected as an argument andThen . Function is not the only type with a method called andThen , so the compiler cannot expect 100% of the time to make a conversion from a method to a function.
source share