Assume we have Object that takes function as parameter of apply
method:
object Wrapper {
def apply(block: TypeA => String) = {
TypeA a = ...
block(a)
}
}
TypeA
is domain type of application.
Now when I define inline block I can define TypeA
parameter as implicit:
Wrapper { implicit a => functionThatUseImplicitA() }
But what if block
parameter is not Function1
, but Function2
? How can I define both parameters as implicit?
object Wrapper2 {
def apply(block: (TypeA, TypeB) => String) = {
TypeA a = ...
TypeB b = ...
block(a, b)
}
}
This one does not work:
Wrapper { implicit (a, b) => functionThatUseImplicitAB() }
The only workaround is define them as vals:
Wrapper { (a, b) =>
implicit val ia = a
implicit val ib = b
functionThatUseImplicitAB()
}
Thanks!
According to the SLS 6.23 Anonymous Functions implicit
keyword is allowed only for single argument functions:
Expr ::= (Bindings | [‘ implicit ’] id | ‘_’) ‘=>’ Expr
ResultExpr ::= (Bindings | ([‘ implicit ’] id | ‘_’) ‘:’ CompoundType) ‘=>’ Block
So you can't make two function parameters as implicit.
This is the one of reasons to use curried functions:
object Wrapper {
def apply(block: TypeA => TypeB => String) = ???
}
Wrapper { implicit a => implicit b =>
functionThatUseImplicitAB()
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.