2012-01-10 55 views
3

我正在努力了解如何尽可能以干/简单的方式使用Scala的抽象类型。比方说,我有以下几点:我可以在Scala抽象类型中使用'嵌套'来简化类定义吗?

trait Product 
trait Pallet[A <: Product] 
class Import[ 
    A <: Product, 
    B <: Pallet[A]] { 

    def offload(): List[A] = { 
    ... 
    } 
} 

class Fridge extends Product 
class FridgePallet extends Pallet[Fridge] 

val fridges = new Import[Fridge, FridgePallet]() 

这工作,但感觉有点冗长 - 因为编译器知道FridgePallet键入与Fridge,有没有简化Import类的打字去除的需要的一种方式明确的A <: Product声明?我想我正在寻找类似如下(不工作):

class Import[B <: Pallet[A <: Product]] { 
    def offload(): List[A] = ... 
} 
val fridges = new Import[FridgePallet]() 

我也试图与_小号取代A秒 - 但后来我不得不使用.asInstanceOf[List[Fridge]]铸造得到在offload()输出上返回类型特异性。

我在想什么/没有理解?

回答

4

我没有看到一个办法做到这一点,而与一般类型住,但如果你能使用类型成员,而不是,你将会得到:

trait Product 
trait Pallet { 
    type A <: Product 
} 
class Import[B <: Pallet] { 
    def offload(): List[B#A] = { ... } 
} 

class Fridge extends Product 
class FridgePallet extends Pallet { 
    type A = Fridge 
} 

val fridges = new Import[FridgePallet]() 
+0

非常感谢** **阿列克谢 - 这工作:'卸载'返回一个'List [Fridge]'。我相信你是对的 - 没有办法用泛型来做到这一点,我不知道有一种方法可以获得** iron9light **的混合方法(泛型在父特征中设置一个类型成员)工作... – 2012-01-10 11:58:57

2
trait Pallet[A <: Product] { 
    type ptype = A 
} 

class Import[P <: Pallet[_]] { 
    def offload(): List[P#ptype] = ... 
} 
+0

谢谢iron9light - 这很好很简洁,不幸的是'List [P#ptype]'在使用时解析成'List [Any]',所以我没有真正获得任何东西...... – 2012-01-10 11:55:45