gpt4 book ai didi

scala - 构造函数的按名称参数

转载 作者:行者123 更新时间:2023-12-03 23:32:53 25 4
gpt4 key购买 nike

来自 my other question有没有办法让构造函数工作的名称参数?我需要一种方法来提供一个在对象内按需/延迟/按名称执行的代码块,并且该代码块必须能够访问类方法,就好像该代码块是该类的一部分一样.

以下测试用例失败:

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

最佳答案

这是因为当您制作这样的实例时:

val tst = new ByNameCons {
...
}

.. 你实际上是在创建一个匿名类,就像在 java 中一样。上面的代码是一样的:

val tst = new ByNameCons() { ... }

.. 而按名称传递的正确语法是:

val tst = new ByNameCons( { ... } )

您不能像使用函数一样省略构造函数的括号。

关于scala - 构造函数的按名称参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2647141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com