Scala - 创建另一种泛型类型的泛型类型

时间:2018-01-02 11:35:46

标签: scala generics traits

我正在重构一个Java接口,它定义了接口内的所有具体类型(方法接收和返回的类型)。我不想强制执行这些类型约束并希望保持接口通用,输入和输出值类型本身应该是通用的。接口中的某些方法是递归的,因为它们返回在定义特征本身的不同泛型类型中定义的泛型类型。我需要在特征中引用泛型类型。

例如:

trait Product[ID,GROUP] {
  def getProductId : ID // the product ID could be an Int,String, or some other type
  def getGroup : GROUP
}

// define a generic reader for the generic products
trait Reader[Key,Prod <: Product[What should I write here?] {
  def getProduct(key: Key) : Product
  def getProductsInGroup(group : Prod.getGroupType) : Seq[Prod] << How do I reference the Prod.GROUP type parameter?
}

1 个答案:

答案 0 :(得分:1)

您需要另一个类型参数:

 trait Reader[Key, Group, Prod <: Product[Key, Group]] {
     def getProduct(key: Key): Prod
     def getProductIdsInGroup(group: Group): Seq[Prod]
 }

为了记录,我不确定你不喜欢内部类型定义作为替代BTW。不知道你在谈论什么“约束”。

 trait Product { 
   type Id
   type Group
 }

 trait Reader[Prod <: Product] {
    def getProduct(key: Prod#Id) 
    def getProductIdsInGroup(group: Prod#Group): Seq[Prod]
 }