2012-11-05 33 views
2

默认的构造函数参数这是我想怎样做:使用方法的返回值作为斯卡拉

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

这会导致编译器错误。有没有另外一种方法来完成这个?

回答

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

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

你可以写一个次级构造:

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

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

没有书面IDE或编译器,因此有人来修复错别字。

1

您可以使用辅助构造

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

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