Reputation: 848
Why Scala has implementation of method andThen only for Function1 (which takes only one parameter). I don't see any reason why rest of functions does not have such method.
Below we have legal code which will compile:
val firstFunction: String => String = ???
val secondFunction: String => String = ???
firstFunction.andThen(secondFunction)
but this will not compile:
val firstFunction: (String,String) => String = ???
val secondFunction: String => String = ???
firstFunction.andThen(secondFunction)
Upvotes: 3
Views: 304
Reputation: 3120
I guess you would want andThen
to return a Function2
in your firstFunction.andThen(secondFunction)
example.
You can easily add this to Function2
(or any other FunctionN
):
implicit final
class Function2MulticategoryOps[A,B,C](val f: (A,B) => C) extends AnyVal {
def andThen[X](g: C => X): (A,B) => X =
(a,b) => g(f(a,b))
}
tupled
by itself won't help much there: you also need something like untupled
:
// note the awful syntax for functions with domain a tuple
implicit final
class Untuple[A,B,C](val f: ((A,B)) => C) extends AnyVal {
def untupled: (A,B) => C =
(a,b) => f((a,b))
}
As to why the FunctionN
classes lack these methods, I don't know; surely someone would chime in with something related with performance.
PS If you ask me, I think life would be easier if there will be no FunctionN
classes, and functions of several arguments would simply be functions with domain a product type; all this FunctionN
business is just a convoluted and partial implementation of the representable multicategory coming from a category with products.
Upvotes: 1
Reputation: 149538
I don't see any reason why rest of functions does not have such method.
Because it is trivial to transform a Function2[String, String, String]
to a Function1[(String, String), String]
, using Function.tupled
:
firstFunction.tupled andThen secondFunction
This will work for functions of any arity.
Upvotes: 5