Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use implicit parameters when defining routing directives?

I have a directive, defined like

def allowedRoles(roles: UserRole*)(implicit login: Login): Directive0 = ???

But I don;t seem to be able to use it in without having to explicitly pass in the login parameter

def myRoutes(implicit req: HttpRequest, login: Login) = {
  path("example" / "path") {
    get {
      allowedRoles(Administrator) { // ← fails 😞
        handleGet
      }
    }
  }
}

if I try to compile this it fails with a type mismatch:

[error]  found   : akka.http.scaladsl.server.Route
[error]     (which expands to)  akka.http.scaladsl.server.RequestContext => scala.concurrent.Future[akka.http.scaladsl.server.RouteResult]
[error]  required: com.example.Login
[error]         allowedRoles(Administrator) { handleGet } }

if I change the marked line to allowedRoles(Administrator)(login) then it works, but it seems like I should not need to do this, what am I missing?

like image 442
Ian Phillips Avatar asked Dec 04 '15 11:12

Ian Phillips


People also ask

What are implicit parameters?

What Are Implicit Parameters? Implicit parameters are similar to regular method parameters, except they could be passed to a method silently without going through the regular parameters list. A method can define a list of implicit parameters, that is placed after the list of regular parameters.

What is the use of implicit in Scala?

Scala implicit allows you to omit calling method or parameter directly. For example, you can write a function that converts int to/from string explicitly but you can ask the compiler to do the same thing for you, implicitly.

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.


1 Answers

This happens because by Scala rules, { handleGet } is considered the second parameter list of allowedRoles. To fix this, make it clear it's actually the parameter of Directive0.apply:

allowedRoles(Administrator).apply { handleGet }
like image 149
Alexey Romanov Avatar answered Nov 07 '22 05:11

Alexey Romanov