在文件https://github.com/playframework/playframework/blob/master/framework/src/play/src/main/scala/play/api/mvc/Security.scala中,注释中包含以下示例代码:
//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)
}
所以我试着写一些类似的代码:
def test1(a: =>Int=>Int=>Int):String="1"
test1 {1 => 1 => 1} // But this line doesn't compile.
我调用它的方式与调用isAuthenticated
的方式相同,为什么我的代码不能编译?
答案 0 :(得分:1)
看看将def test1(a: =>Int=>Int=>Int):String="1"
粘贴到Scala REPL中时会发生什么:
test1: (a: => Int => (Int => Int))String
test
被定义为接受另一个函数作为其参数的函数。注意REPL输出中的额外括号。 a
是一个将Int
映射到另一个函数 Int => Int
的函数。
所以这样的事情会更合适:
def a(i: Int): Int => Int = {j: Int => i + j}
test1(a)
答案 1 :(得分:1)
test1 {1 => 1 => 1}
无法编译,因为{1 => 1 => 1}
不是有效的函数定义。另一方面,{x => y => 1}
确实编译。这是因为1
不能用作参数的名称。