简体   繁体   English

Scala:Play2中的def vs val

[英]Scala: def vs val in Play2

I have been following the instruction in the Play! 我一直在按照游戏中的说明进行操作! Framework Essentials book, and sometimes I see an action in controllers defined with a def , and sometimes with a val . Framework Essentials一书,有时候我会在使用def定义的控制器中看到一个动作,有时候会使用val

I know that def will reevaluate the expression when called, and val will immediately evaluate the expression, but in the context of a controller action, is there any difference? 我知道def会在调用时重新评估表达式,val会立即评估表达式,但在控制器操作的上下文中,有什么区别吗?

Here is the sample code: 以下是示例代码:

object Items extends Controller {

  val list = Action { implicit request =>
    ...
  }

  val create = Action { implicit request =>
    ...
  }

  def details(id: Long) = Action { implicit request =>
    ...
  }

  def update(id: Long) = Action { implicit request =>
    ...
  }
}

As you said, def will reevaluate the expression every time it is called, while val will be evaluated when the Items object is instantiated. 正如您所说, def将在每次调用时重新评估表达式,而val将在实例化Items对象时进行评估。

The implications of this is that the controller actions defined in terms of a def will be slower as every time it is called, the controller needs to instantiate an Action , pass it the anonymous function that you have defined,...etc. 这样做的含义是,根据def定义的控制器动作每次调用时都会变慢 ,控制器需要实例化一个Action ,将它传递给你定义的匿名函数,等等。

If the expression does not require any abstraction, it will always be more performant to use val as opposed to def . 如果表达式不需要任何抽象,那么使用val而不是def将始终更def

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM