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?
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.
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.
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.
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 }
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