0

I wrote a method that returns objects that all extend a common trait. I want to specify the return type to be objects with that trait. The complication is that the trait has a recursive type signature.

In particular, I am using elastic4s and looking at the aggregationDefinition trait. The trait definition is:

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

And a simplified version of my method is:

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

The complication lies with AggregationDefinition, that it requires type parameters:

Error: trait AggregationDefinition takes type parameters

I am confused by the recursion and the cross reference in the trait definition, and it is unclear to me what the type parameters should be. What should I use for the type parameters?

sksamuel
  • 16,154
  • 8
  • 60
  • 108
canzar
  • 340
  • 4
  • 17

1 Answers1

0

The AggregationDefinition need type Bound(see the type signature), you can use AbstractAggregationDefinition, like:

def asAggregation(): AbstractAggregationDefinition = {
  aggType match {
    case "terms" => aggregation.terms(aggName).field(key)
    case "cardinality" => aggregation.cardinality(aggName).field(key)
  }
}
chengpohi
  • 14,064
  • 1
  • 24
  • 42
  • What you are suggesting works just fine. However, I need to call `aggregations` on the objects returned by `asAggregation`. I want to return `AggregationDefinition` because that is where `aggregations` is defined. – canzar Jun 29 '16 at 11:47