gpt4 book ai didi

scala - 从 Play 框架 zentask 示例中了解 Scala 函数

转载 作者:行者123 更新时间:2023-12-01 01:07:05 24 4
gpt4 key购买 nike

这是 Application.scala 中 zentask 示例中的一个函数。
我试图理解它...

f: => 字符串是什么意思?

f: => String => Request[AnyContent] => Result 的链接怎么样

/** 
* Action for authenticated users.
*/
def IsAuthenticated(f: => String => Request[AnyContent] => Result) =
Security.Authenticated(username, onUnauthorized) { user =>
Action(request => f(user)(request))
}

最佳答案

形式为 fn: => String 的参数表示返回(或为)字符串的“生成器”(函数或值),因此,例如,您可能有一个方法定义为

def myMethod(fn: => String): String = "Fn output = " + fn

并按如下方式调用它(我在这里使用的返回类型通常可以由编译器推断,我只是出于教学目的添加它们):
def myFn: String = "Hello!"
// Alternatively: def myFn(): String = "Hello!"
// or: val myFn: () => String = "Hello!"
// or most simply: val myString = "Hello!"

val output = myMethod(myFn) // output = "Fn output = Hello!"

在此基础上,我们可以定义一个方法,该方法采用将 String 转换为 Int 的函数,例如:
def my2ndMethod(fn: String => Int): Int = fn("4")

并按如下方式调用它:
def my2ndFn(input: String) = 5 * input.toInt
// Alternatively: val my2ndFn: String => Int = input => 5 * input.toInt

val output2 = my2ndMethod(my2ndFn _) // output2 = 20

在您提供的情况下,您有一个更复杂的实体:返回(或者是)一个函数,该函数接受一个 String 并返回一个进一步的函数,该函数又接受一个 Request[AnyContent]并且(最后)返回一个结果(呸!)。

您也可以将其视为采用如下定义和使用的函数:
def authFn(username: String)(request: Request[AnyContent]): Result

val authenticatedResult = IsAuthenticated(authFn _)

关于scala - 从 Play 框架 zentask 示例中了解 Scala 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17960092/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com