Reputation: 8281
I have the following code :
def a = f(aa)
def b = f(bb)
def c = f(cc)
def d = f(dd)
Is there a solution to remove the boilerplate, i.e. explicit call to f
Upvotes: 0
Views: 135
Reputation: 3696
You could do something like this with the standard library:
val List(a,b,c,d) = List(aa,bb,cc,dd).map(f)
It uses pattern matching to assign the values on the left, which will fail at runtime if the two List
s aren't the same length.
Scalaz has a more type-safe option that uses tuples to ensure the number of values on the left and right are the same (checked at compile time):
import scalaz._, Scalaz._
val (a,b,c,d) = (aa,bb,cc,dd).map(f)
Upvotes: 6
Reputation: 3294
You can use implicit: http://docs.scala-lang.org/overviews/core/implicit-classes.html
val aa: Int = 1
// Let's say that your function f returns instance of C
def f(x: Int): C = ???
implicit class C(in: Int) {
// Do whatever you need here ...
}
def a: C = aa
Upvotes: 1