scala - 在默认值中引用 Scala 构造函数参数

标签 scala constructor arguments

在下面的 Scala 代码中,编译器告诉我 not found: value x 当我尝试更新 y 的默认值时,引用 x ,另一个构造函数参数。

class Foo(x: String, y: Bar = new Bar(x))

class Bar(a: String)

我相信这种限制是有充分理由的。任何人都可以阐明一些想法并可能提供替代方法吗?

最佳答案

作为替代方法:

class Foo(x: String, y: Bar)

class Bar(a: String)

object Foo {
  def apply(x: String) = new Foo(x, new Bar(x))
}

另一个:

class Foo(x: String, y: Bar) {
  def this(x: String) = this(x, new Bar(x))
}

关于scala - 在默认值中引用 Scala 构造函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21508939/

相关文章:

scala - 使用 ReactiveMongo 插入后获取 ID

function - 带整数参数的分段 numpy 函数

python - 检测无效的关键字参数

Angular:在窗口上的事件监听器中引用当前组件

c++ - 类 header.h 不包含在 main 中

c++ - 继承类中的构造函数调用

jsf - 在 EL 中调用直接方法或带参数/变量/参数的方法

scala - Scala中的letrec? (不可变的方式 "Tie the knot?")

scala - 如何创建一个只接受可以使用 spray-json 转换为 Json 的类型的函数

scala - 在 Scala 中创建一个懒惰的 var