【发布时间】:2013-02-08 15:56:40
【问题描述】:
在 Play scala html 模板中,可以指定
@(标题:字符串)(内容:Html)
或
@(title: String)(content: => Html)
有什么区别?
【问题讨论】:
在 Play scala html 模板中,可以指定
@(标题:字符串)(内容:Html)
或
@(title: String)(content: => Html)
有什么区别?
【问题讨论】:
写入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)
在方法执行之前同时评估then 和else 是一种浪费。我们知道只会执行其中一个表达式,条件是true 或false。这就是 when 和 else 被定义为“按名称”参数的原因。
Scala 课程中解释了这个概念:https://www.coursera.org/course/progfun
【讨论】: