ang*_*okh 2 scala playframework-2.0
在 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
Run Code Online (Sandbox Code Playgroud)
按名称参数在使用时执行。问题在于它们可以被多次评估。
一个很好的例子是 if 语句。假设是这样的方法:
def if(condition:Boolean, then: => String, else: => String)
Run Code Online (Sandbox Code Playgroud)
这将是评估既浪费then和else执行方法之前。我们知道只有一个表达式会被执行,条件是trueor false。这就是原因,when并被else定义为“按名称”参数。
这个概念在 Scala 课程中有解释:https : //www.coursera.org/course/progfun