繁体   English   中英

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

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

我正在重构一个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?
}

您需要另一个类型参数:

 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]
 }

暂无
暂无

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

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