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!
The implicit parameter in Java is the object that the method belongs to. It's passed by specifying the reference or variable of the object before the name of the method. An implicit parameter is opposite to an explicit parameter, which is passed when specifying the parameter in the parenthesis of a method call.
Implicit parameters are the parameters that are passed to a function with implicit keyword in Scala, which means the values will be taken from the context in which they are called.
A method or constructor can have only one implicit parameter list, and it must be the last parameter list given. A method with implicit parameters can be applied to arguments just like a normal method.
An implicit argument of a function is an argument which can be inferred from contextual knowledge. There are different kinds of implicit arguments that can be considered implicit in different ways. There are also various commands to control the setting or the inference of implicit arguments.
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()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With