[英]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.