2012-12-21 44 views
2

我一直在努力解決這個煩人的問題一段時間沒有找到一個優雅的解決方案。斯卡拉,類層次結構和構造函數複製/粘貼

比方說,我有這樣的類層次結構:初值的

class StatWithBounds[A](val min: A, val max: A, val currentValue: A) 
class StatBetween0And20(initialValue: Int) extends StatWithBounds[Int](0, 20, initialValue) 
class PositiveStatOnly(initialValue: Int) extends StatWithBounds[Int](0, Integer.MAX_VALUE, initialValue) 
class UncappedPercentage(initialValue: Int) extends StatWithBounds[Int](0, Integer.MAX_VALUE, initialValue) 

複製/粘貼過於冗長。此外,如果我想做這樣的事情:

class Strength(initialValue: Int) extends StatBetween0And20(initialValue) 
class Intelligence(initialValue: Int) extends StatBetween0And20(initialValue) 
class Piety(initialValue: Int) extends StatBetween0And20(initialValue) 

什麼是複製/粘貼(並想象我有10個以上的子類)!

有沒有一種優雅的方式來解決這個混亂的問題?

+1

可能的重複[在Scala中創建子類的快捷方式,無需重複構造函數參數?](http://stackoverflow.com/questions/1653942/shortcut-for-subclassing-in-scala-without-repeating-constructor-arguments) –

+0

默認值? – pedrofurla

回答

5

您可以使用特徵,而是如果你不需要原始類:

trait StatWithBounds[A] { 
    def min: A 
    def max: A 
    def currentValue: A 
} 

trait StatBetween0And20 extends StatWithBounds[Int] { 
    def min = 0 
    def max = 20 
} 

class Strength(val currentValue: Int) extends StatBetween0And20 
class Intelligence(val currentValue: Int) extends StatBetween0And20 
... 

或者,你根本無法使用這麼長的變量名!

class Stat[A](val min: A, val max: A, val current: A) 
class Stat20(i: Int) extends Stat[Int](0, 20, i) 
class Strength(i: Int) extends Stat20(i) 
class Intelligence(i: Int) extends Stat20(i) 
... 

看看有多少噪音是?長變量名稱是樣板的一種形式。有時候爲了清晰起見,你需要它,但通常不會將參數傳遞給構造函數。

+0

非常適合兩種不同的方法! –