Reputation: 4004
As Scala provides a way to write function literals, which one is quite recommended?
For example I want to a flatMap
or map
on some object, I need to pass a function from f: A => B
or similar.
For this function, we can use both function literals and a private normal method(Java way) in the class?
Upvotes: 0
Views: 130
Reputation: 8495
Function literals are instances of the different function traits, and as such they have some methods defined on them (andThen
, compose
, apply
, toString
): Function1
Partial functions have even more methods: PartialFunction
In many cases, the compiler allows you to put methods in places that expect function literals, so more often than not there is no difference. Partially applying a method (e.g. myMethod _
) even converts it to a function literal, so that's even less of a reason to think too much about this.
In the end, you should use function-literals whenever you need to treat functionality as data, and I don't see any reason why you would use them otherwise.
Upvotes: 1