【问题标题】:scala colon right arrow key vs only colon [duplicate]scala冒号右箭头键与仅冒号[重复]
【发布时间】:2013-02-08 15:56:40
【问题描述】:

在 Play scala html 模板中,可以指定

@(标题:字符串)(内容:Html)

@(title: String)(content: => Html)

有什么区别?

【问题讨论】:

    标签: scala playframework-2.0


    【解决方案1】:

    写入parameter: => Html 称为“按名称参数”。

    例子:

    def x = {
      println("executing x")
      1 + 2
    }
    
    def y(x:Int) = {
      println("in method y")
      println("value of x: " + x)
    }
    
    def z(x: => Int) = {
      println("in method z")
      println("value of x: " + x)
    }
    
    y(x)
    //results in:
    //executing x
    //in method y
    //value of x: 3
    
    z(x)
    //results in:
    //in method z
    //executing x
    //value of x: 3
    

    按名称参数在使用时执行。这样做的问题是它们可以被多次评估。

    if 语句就是一个很好的例子。假设如果是这样的方法:

    def if(condition:Boolean, then: => String, else: => String)
    

    在方法执行之前同时评估thenelse 是一种浪费。我们知道只会执行其中一个表达式,条件是truefalse。这就是 whenelse 被定义为“按名称”参数的原因。

    Scala 课程中解释了这个概念:https://www.coursera.org/course/progfun

    【讨论】:

      猜你喜欢
      • 2019-06-30
      • 2011-11-29
      • 2012-01-02
      • 2019-09-14
      • 2016-11-04
      • 2014-12-27
      • 1970-01-01
      • 2021-10-21
      • 1970-01-01
      相关资源
      最近更新 更多