我想知道scala是否可以这样做: 假设我有以下课程:
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可以是Sell或Buy,取决于它的类型参数。
答案 0 :(得分: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在运行时从不实例化,它们仅存在于编译器中