Jordan Cutler
Jordan Cutler

Reputation: 582

Scala - Extend Generic Type Parameter

Sorry if this is a duplicate. Had trouble finding with some basic searches.

If I have

trait Container[T] { data: T } 

I'm trying to have a trait extend Container such that data is a Traversable[T].

Would the following do that, and what does it mean/how would you read it?

trait Extension[T] extends Container[Traversable[T]]

Upvotes: 1

Views: 867

Answers (2)

Dmytro Mitin
Dmytro Mitin

Reputation: 51658

Just in case, if you want to abstract over a more specific collection type (Traversable or Iterable can be too general), you can consider

trait Extension[T, S <: Traversable[T]] extends Container[S]

or

trait Extension[T, S[t] <: Traversable[t]] extends Container[S[T]]

Upvotes: 0

francoisr
francoisr

Reputation: 4585

Yes, Extension[T] is a Container[Traversable[T]], which means it can only hold Traversable[T] as data.

Note that you might want to define Extension[+T] instead of Extension[T] (and do this for Container as well). This will means that Extension[Cat] is a subclass of Extension[Animal].

Upvotes: 1

Related Questions