2012-10-24 71 views
14

我有一个斯卡拉类:实例化从Java Scala的类,并使用构造函数的默认参数

class Foo(val x:String = "default X", val y:String = "default Y") 

我想从调用它的Java,但使用默认参数

null不工作(其分配null,如预期)

new Foo(null,null); //both are instantiated as null 

这一招确实为我工作,但它的丑陋,我不知道是否有更好的办法:

斯卡拉

class Foo(val x:String = "default X", val y:String = "default Y") { 
    def this(x:Object) = this() 
} 

的Java

new Foo(null); //no matter what I pass it should work 

不过,我想喜欢摆脱构造函数重载技巧,并使用0参数构造函数

这可能吗?

回答

7

看来,有没有这样的办法:https://issues.scala-lang.org/browse/SI-4278

问题:默认的无参数的构造应的类的所有可选参数
生成...

卢卡斯Rytz:关于语言的一致性,我们决定不修复这个问题 - 因为它是一个与框架互操作的问题,我们认为它不应该固定在语言层面。

解决方法:重复默认,或抽象超过一个,或放一个默认的int无参数的构造函数

然后卢卡斯提出了同样的解决方案,你发现:

class C(a: A = aDefault, b: B = C.bDefault) { 
    def this() { this(b = C.bDefault) } 
} 
object C { def bDefault = ... } 

// OR 

class C(a: A = aDefault, b: B) { 
    def this() { this(b = bDefault) } 
} 
1

更普遍如果您有一个带默认参数的Scala类,并且您希望在Java中重写实例化覆盖0,1个或更多默认值而不必指定全部,请考虑扩展Scala API以在伴随对象中包含Builder。

case class Foo(
    a: String = "a", 
    b: String = "b", 
    c: String = "c") 

object Foo { 
    class Builder { 
    var a: String = "a" 
    var b: String = "b" 
    var c: String = "c" 
    def withA(x: String) = { a = x; this } 
    def withB(x: String) = { b = x; this } 
    def withC(x: String) = { c = x; this } 
    def build = Foo(a, b, c) 
    } 
} 
相关问题