简体   繁体   中英

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 .

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?

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.

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.

If the expression does not require any abstraction, it will always be more performant to use val as opposed to def .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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