构造函数的名称参数 [英] By-Name-Parameters for Constructors
问题描述
来自我的其他问题有没有一种方法可以获取构造函数的名称参数?我需要一种方法来提供按需在对象内按需/惰性/按名称执行的代码块,并且该代码块必须能够访问类方法,就像该代码块是类的一部分一样
coming from my other question is there a way to get by-name-parameters for constructors working? I need a way to provide a code-block which is executed on-demand/lazy/by-name inside an object and this code-block must be able to access the class-methods as if the code-block were part of the class.
以下测试用例失败:
package test
class ByNameCons(code: => Unit) {
def exec() = {
println("pre-code")
code
println("post-code")
}
def meth() = println("method")
def exec2(code2: => Unit) = {
println("pre-code")
code2
println("post-code")
}
}
object ByNameCons {
def main(args: Array[String]): Unit = {
val tst = new ByNameCons {
println("foo")
meth() // knows meth() as code is part of ByNameCons
}
tst.exec() // ByName fails (executed right as constructor)
println("--------")
tst.exec2 { // ByName works
println("foo")
//meth() // does not know meth() as code is NOT part of ByNameCons
}
}
}
输出:
foo
method
pre-code
post-code
--------
pre-code
foo
post-code
推荐答案
这是因为在创建这样的实例时:
This is because when you're making an instance like this:
val tst = new ByNameCons {
...
}
..实际上,您正在创建一个匿名类,例如在Java中。
上面的代码与以下内容相同:
.. you're actually creating an anonymous class, like in java. The above code is the same as:
val tst = new ByNameCons() { ... }
..而通过名称传递的正确语法是:
.. while the correct syntax for passing by-name is:
val tst = new ByNameCons( { ... } )
构造函数的括号不能与函数的省略。
You cant omit parentheses the same way for constructors as with functions.
这篇关于构造函数的名称参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!