2012-10-24 76 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) 
    } 
} 
相關問題