Orest
Orest

Reputation: 6748

Scala upper bound for generic in field

I have next field:

var operations = Map.empty[Long, _ <: Operation]

I want to get second generic parameter upper bound extends Operation class. When I'm doing like above I have error unbound wildcard type.

How can I achieve this?

Upvotes: 0

Views: 304

Answers (2)

Michael Zajac
Michael Zajac

Reputation: 55569

I'm going to address the actual error at hand. As unnecessary as it is, it will work if you define it like this:

var operations: Map[Long, _ <: Operation] = Map.empty // Or some Map that conforms

The difference is that in the above code, we're saying operations has type Map[Long, _ <: Operation] -- which is a map from Long to some type that we don't care about, so long as it is bounded above by Operation. But Map.empty is a method call which expects some actual types to be supplied as type-parameters (or will be inferred as Nothing) and not an existential.

Of course, this is all unnecessary because Map is covariant over its second type parameter. That means that if you have some Z that is a sub-type of Operation, then Map[Long, Z] is a sub-type of Map[Long, Operation].

Upvotes: 1

andyczerwonka
andyczerwonka

Reputation: 4260

Map is defined as trait Map[A, +B], so Operation is covariant - an upper-bound type in this example.

Just say Map.empty[Long, Operation]

Upvotes: 2

Related Questions