隐含:如何让隐含值生效?

时间:2014-06-17 06:13:35

标签: scala

如何让隐含值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)
}

1 个答案:

答案 0 :(得分:2)

test没有(并且不能)知道f的第二个参数是隐含的。你可以写

def test(f: =>Int=>Int=>Int)={
   f(1)(implicitly[Int])
}

需要隐式Int在范围内(在您的情况下为p2)。

此外,似乎没有理由让testisAuthenticated按名称(即=>Int=>Int=>Int而不是Int=>Int=>Int)进行论证,它是'我只是增加开销。