0

我写了一个方法,它返回的对象都扩展了一个共同的特征。我想将返回类型指定为具有该特征的对象。复杂之处在于该特征具有递归类型签名。

特别是,我正在使用elastic4s并查看aggregationDefinition trait。特征定义为:

trait AggregationDefinition[+Self <: AggregationDefinition[Self, B], B <: AggregationBuilder[B]]

我的方法的简化版本是:

def asAggregation(): AggregationDefinition = {
  aggType match {
    case "terms" => aggregation.terms(aggName).field(key)
    case "cardinality" => aggregation.cardinality(aggName).field(key)
  }
}

复杂性在于 AggregationDefinition,它需要类型参数:

Error: trait AggregationDefinition takes type parameters

我对特征定义中的递归和交叉引用感到困惑,我不清楚类型参数应该是什么。我应该为类型参数使用什么?

4

1 回答 1

0

AggregationDefinition需要类型Bound(见类型签名),可以使用AbstractAggregationDefinition,比如:

def asAggregation(): AbstractAggregationDefinition = {
  aggType match {
    case "terms" => aggregation.terms(aggName).field(key)
    case "cardinality" => aggregation.cardinality(aggName).field(key)
  }
}
于 2016-06-29T01:53:29.247 回答