在默认值中引用 Scala 构造函数参数 [英] Reference Scala constructor args in default value
本文介绍了在默认值中引用 Scala 构造函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在以下 Scala 代码中,当我尝试更新 y
的默认值时,编译器告诉我 not found: value x
,引用 x
,另一个构造函数参数.
In the following Scala code, the compiler is telling me not found: value x
when I try to new up my default value for y
, referencing x
, another constructor argument.
class Foo(x: String, y: Bar = new Bar(x))
class Bar(a: String)
我相信这种限制是有充分理由的.任何人都可以阐明并可能提供替代方法吗?
I trust there's good reason for this limitation. Can anyone shed some light and possibly offer an alternative approach?
推荐答案
作为替代方法:
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 构造函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文