Scala 实现内联特征方法

Scala implement inline trait method

我已经开始学习 scala 和 play 框架。我从 play framework 站点下载了示例项目。我有一个新手问题,因为我无法理解以下语法:

def count = Action { Ok(counter.nextCount().toString) }

它具体是做什么的? Action 是在 BaseController 中实现的功能,其中分配了动作生成器。 beetwen 括号的内容是什么?在这种情况下大括号是什么意思?

源码给你详细介绍:

/**
   * Constructs an `Action` with default content, and no request parameter.
   *
   * For example:
   * {{{
   * val hello = Action {
   *   Ok("Hello!")
   * }
   * }}}
   *
   * @param block the action code
   * @return an action
   */
  final def apply(block: => Result): Action[AnyContent] =
    apply(BodyParsers.utils.ignore(AnyContentAsEmpty: AnyContent))(_ => block)

相当于def count = Action.apply(Ok(counter.nextCount().toString))

在 playframework 中,请求由 Actions 处理。当您调用 Action { ... } 时,您实际上是在调用 play.api.mvc.Action 辅助对象来创建 Action 值。

object Action extends ActionBuilder[Request] { ... } 

如果你仔细观察 Action 对象,它会扩展到 play.api.mvc.ActionBuilder 特征。此特征包含创建 Action 值的各种 overloaded apply 方法。因此,当您调用 Action{ ... } 时,您实际上是在调用 Action.apply({...}) 并且此 apply 方法继承自 ActionBuilder 特征。如果你研究 ActionBuilder 特征,你会看到各种更高阶的 apply 函数。

现在在你的情况下,def count = Action { Ok(counter.nextCount().toString) }

您实际上是在调用具有默认内容且没有请求参数的 apply 方法。

final def apply(block: => Result): Action[AnyContent] = apply(_ => block)

这意味着,您正在提供 { Ok(counter.nextCount().toString) } return Ok 结果块。

小括号的内容是什么?在这种情况下大括号是什么意思?

当您执行 Action { Ok(counter.nextCount().toString) } 时,您实际上是在调用:

Action.apply(Ok(counter.nextCount().toString))

在 scala 中,apply 方法是一个工厂方法,因此您实际上不必调用 apply 方法,因此您也可以这样做 Action(Ok(counter.nextCount().toString))。此外,如果您的函数仅采用单个参数,则可以将 () 括号替换为大括号 {}。即你可以做 Action{Ok(counter.nextCount().toString)}.

我建议研究一下函数字面量、高阶函数、别名参数、方法柯里化等。这样,您将对这些有更深入的了解。