简体   繁体   English

Scala-创建采用另一种通用类型的通用类型

[英]Scala - create a generic type taking another generic type

I'm refactoring a Java interface which defines all the concrete types inside the interface (the types that the methods are receiving and returning). 我正在重构一个Java接口,该接口定义了接口内的所有具体类型(方法正在接收和返回的类型)。 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?
}

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. 作为记录,我不确定您不喜欢内部类型定义作为替代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]
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM