使用方法返回值作为Scala中的默认构造函数参数

时间:2012-11-05 14:48:12

标签: scala

这就是我想做的事情:

object foo {
    def bar = Array(1, 2, 3, 4, 5)
}
class foo (baz = bar) {
}

这会导致编译器错误。还有另一种方法可以实现这个目标吗?

3 个答案:

答案 0 :(得分:12)

object foo {
    def bar = Array(1, 2, 3, 4, 5)
}

class foo (baz: Array[Int] = foo.bar) {
}

答案 1 :(得分:1)

你可以写一个辅助构造函数:

object foo {
    def bar = Array(1, 2, 3, 4, 5)
}

class foo (baz : Array[Int]) {
    def this(){
        this(bar)
    }
}

没有IDE或编译器编写,所以有人必须修复拼写错误。

答案 2 :(得分:1)

您可以使用辅助构造函数

object Foo {
  def bar = Array(1, 2, 3, 4, 5)
}

class Foo(baz: Array[Int]) {
  def this() = this(Foo.bar)
}
相关问题