0
votes

I'm refactoring a Java interface which defines all the concrete types inside the interface (the types that the methods are receiving and returning). I don't want to enforce those type constraints and wish to keep the interface generic, the input and output value types should themselves be generic. Some of the methods in the interface are recursive in the sense that they return generic type defined inside a different generic type defining the trait itself. I need to reference the generic types inside the trait.

For instance:

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

1 Answers

1
votes

You need another type parameter:

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

For the record, I am not sure what it is you don't like about inner type definitions as an alternative BTW. Don't know what "constraints" you are talking about.

 trait Product { 
   type Id
   type Group
 }

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