How to define function literal with multiple implicit arguments in Scala? I've tried this way:
def create = authAction { (implicit request, user) ⇒ // Syntax error
Ok(html.user.create(registrationForm))
}
but it throws compilation error.
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.
Every object in C++ has access to its own address through an important pointer called this pointer. The this pointer is an implicit parameter to all member functions. Therefore, inside a member function, this may be used to refer to the invoking object.
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.
As stated in previous answer, you can only define a single implicit parameter for a function literal, but there is workaround.
Instead of multiple implicit arguments you can write function literal as taking multiple argument lists with one argument each. Then it is possible to mark each argument as implicit. Rewriting original snippet:
def create = authAction { implicit request ⇒ implicit user ⇒
Ok(html.user.create(registrationForm))
}
You can call it from authAction
as f(request)(user)
.
implicit
keyword duplication is annoying, but at least it works.
From what I can understand of the language specification, as of version 2.9.2 you can only define a single implicit parameter for anonymous functions.
E.g.
val autoappend = {implicit text:String => text ++ text}
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