2014-02-28 60 views
2

我不知道這樣的事情是可能的斯卡拉: 假設我有以下類:斯卡拉延伸取決於參數

trait Condition 
trait BuyCondition extends Condition 
trait SellCondition extends Condition 

class OrCondition[C <: Condition](c1: C, c2: C) extends Condition 

是這可能使它的工作是這樣的:

val buyOr: BuyCondition = new OrCondition[BuyCondition](bc1, bc2) 
val sellOr: SellCondition = new OrCondition[SellCondition](sc1, sc2) 

基本上我希望OrCondition可以是銷售或購買,具體取決於它的類型參數。

回答

1

是的,你可以使用phantom types

下面是一個例子

// Define a base trait for the condition phantom type 
object Condition { 
    trait Type 
} 

// The Condition is paramaterised by the phantom type 
trait Condition[T <: Condition.Type] 

// Define Buy/Sell types 
trait BuyType extends Condition.Type 
trait SellType extends Condition.Type 

// defin the buy/Sell conditions 
type BuyCondition = Condition[BuyType] 
type SellCondition = Condition[SellType] 

class OrCondition[T <: Condition.Type](c1: Condition[T], c2: Condition[T]) extends Condition[T] 

val bc1, bc2 = new BuyCondition {} 
val sc1, sc2 = new SellCondition {} 

val buyOr: BuyCondition = new OrCondition(bc1, bc2) 
val sellOr: SellCondition = new OrCondition(sc1, sc2) 

注意,他們被稱爲幻影類型,因爲類型BuyType和SellType絕不會在運行時實例化它們只存在於編譯器

做到這一點