Scala代码揭开神秘面纱 [英] Scala Code demystify
问题描述
有人可以揭开这个代码的神秘面纱,这是Play20框架中zentasks示例的一部分.我很好奇这是如何工作的,因为我是Java的Scala的新手,所以很多事情很难缠住我的头.
Could someone demystify this code which is part of the zentasks example in the Play20 framework. I'm curious how this works, granted I'm new to Scala from Java so a lot of things are tough to wrap my head around.
def IsAuthenticated(f: => String => Request[AnyContent] => Result) =
Security.Authenticated(username, onUnauthorized) { user =>
Action(request => f(user)(request))
}
推荐答案
您需要对签名进行一些拆分. f
是接受尚未计算的字符串=> String
并返回接受Request[AnyContent]
并返回结果的另一个函数的函数.
You need to split up the signature a bit. f
is a function that takes a not-yet-computed string => String
and returns another function that accepts a Request[AnyContent]
and returns a result.
Security.Authenticated
调用接受两个参数列表.具有username
和onUnauthorized
的一个.第二个函数具有接受用户并返回操作的功能.
The Security.Authenticated
call accepts two parameters lists. One that has username
and onUnauthorized
. The second takes a function accepting the user and returning an action.
Action.apply
方法接受功能Request[AnyContent] => Result
因此,f以"curried"方式被调用.那是第一个函数被调用,然后结果函数立即被使用f(user)(request)
.
so, the f is called in 'curried' fashion. That is the first function is called, and then the resulting function is immediately used f(user)(request)
.
这是丑陋的(至少,尽我所能)和丑陋的东西:
Here's the same thing desugared (at least, as best I can) and ugly:
def isAuthenticated(f: => String => Request[AnyContent] => Result) =
Security.Authenticated(username, onUnauthorized) { user: String =>
Action.apply { request: Request[AnyContent] =>
val hiddenTmp: Request[AnyContent] => Result = f(user)
hiddenTemp.apply(request)
}
}
您可以看到编译器正在做一些工作来删除类型注释.希望这有助于解释它如何还原成原始scala.本质上,该功能执行很多功能组成.
You can see the compiler is doing a bit of work removing type annotations. Hopefully that helps explain how it desugars into raw scala. Essentially, the function does a lot of functional composition.
这篇关于Scala代码揭开神秘面纱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!