2013-04-09 24 views
12

我有Scala中的一個類,這是目前在標準方式構造:Scala的構造棄用

class Test(int : Int) 
{ 
    override def toString() = "Test: %d".format(int) 
} 

然而,我想通過一個同伴對象移動到間接施工。當我正在修改的庫被其他人使用時,我不想立即將構造函數私有化。相反,我想棄用它,然後在人們有機會更改其使用情況後再回來並將其設爲私有。所以我修改我的代碼是這樣的:

object Test 
{ 
    def apply(int : Int) = new Test(int) 
} 

@deprecated("Don't construct directly - use companion constructor", "09/04/13") 
class Test(int : Int) 
{ 
    override def toString() = "Test: %d".format(int) 
} 

但是,這棄用了整個類。

scala> Test(4) 
<console>:10: warning: class Test in package foo is deprecated: Don't construct directly - use companion constructor 
     val res0 = 
     ^
res0: com.foo.Test = Test: 4 

有誰知道Scala是否支持對構造函數的棄用,如果有的話,它是如何實現的?

回答

10

This thread似乎描述瞭解決方案:

object Test 
{ 
    def apply(int : Int) = new Test(int) 
} 


class Test @deprecated("Don't construct directly - use companion constructor", "09/04/13") (int : Int) 
{ 
    override def toString() = "Test: %d".format(int) 
} 

不能嘗試它,現在雖然。

+1

(編輯)這確實有效,但它不是絕對理想的,因爲在導入此類時您會收到棄用警告,因爲伴隨對象會調用已棄用的構造函數 - 任何想法都會繞過該構造函數? – paulmdavies 2013-04-09 08:42:17

+0

你確定嗎?編譯'Test'時應該得到一個警告,但是在導入它時不會。 – 2013-04-09 09:19:36

+0

你是對的 - 只有在編譯。 – paulmdavies 2013-04-09 09:39:52

1

就我個人的情況而言,由於伴隨對象使用不建議使用的構造函數,在構造函數的廢棄造成編譯時的棄用警告時,一位同事建議我使用僞參數提供第二個構造函數, :

object Test 
{ 
    def apply(int : Int) = new Test(int, false) 
} 


class Test (val int : Int, dummy : Boolean) 
{ 
    @deprecated("Don't construct directly - use companion constructor", "09/04/13") 
    def this(int : Int) = this(int, false) 

    override def toString() = "Test: %d".format(int) 
} 

這工作,因爲只會有廢棄警告,如果用戶調用過時的構造,但顯然這是不愉快的 - 沒有任何人有一個卓越的解決方案?

+0

卓越的解決方案是Jens Schauder已經提供的解決方案 – 2013-04-09 14:01:22

+0

但是,在這個特定案例中,這不是一個真正的解決方案 - 要求用戶用其他警告貶低的東西來取代某些警告是不理想的。 – paulmdavies 2013-04-09 14:11:31

+0

我以爲你已經承認它不會在客戶端代碼上提示棄用(當你**編譯'Test'時你只會收到警告)? – 2013-04-09 14:39:40