揭开playframework(Security.scala)的示例代码的神秘面纱

时间:2014-06-15 07:13:24

标签: scala playframework

在文件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的方式相同,为什么我的代码不能编译?

2 个答案:

答案 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不能用作参数的名称。