Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function literal with multiple implicit arguments

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.

like image 972
lambdas Avatar asked Dec 28 '12 15:12

lambdas


People also ask

What is implicit by the argument of a function?

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.

What is implicit argument in C++?

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.

What is implicit argument in Scala?

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.


2 Answers

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.

like image 85
lambdas Avatar answered Sep 21 '22 15:09

lambdas


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}
like image 36
pagoda_5b Avatar answered Sep 24 '22 15:09

pagoda_5b