如何让隐含值p2生效?
def test(f: =>Int=>Int=>Int)={
f(1) //it won't use the implicit p2.
}
val p1:Int=1
implicit val p2:Int=2 //here define a implicit value
test{a1=>implicit a2=>a1+a2} // here define a implicit function, but how to let it use p2 which defined implicitly?
我试图伪造一个类似于下面调用isAuthenticated的例子,它的singuature为
isAuthenticated {username => 隐含请求=>好的(“你好”+用户名}}
//in a Security trait
def username(request: RequestHeader) = request.session.get("email")
def onUnauthorized(request: RequestHeader) = Results.Redirect(routes.Application.login)
def isAuthenticated(f: => String => Request[AnyContent] => Result) = {
Authenticated(username, onUnauthorized) { user =>
Action(request => f(user)(request))
}
}
//then in a controller
def index = isAuthenticated { username => implicit request =>
Ok("Hello " + username)
}
答案 0 :(得分:2)
test
没有(并且不能)知道f
的第二个参数是隐含的。你可以写
def test(f: =>Int=>Int=>Int)={
f(1)(implicitly[Int])
}
需要隐式Int
在范围内(在您的情况下为p2
)。
此外,似乎没有理由让test
或isAuthenticated
按名称(即=>Int=>Int=>Int
而不是Int=>Int=>Int
)进行论证,它是'我只是增加开销。