I notice the narrow
method exists for sequences. How would one go about doing the opposite, going from sequence of a subclass to a sequence of a superclass in a type-safe manner?
How to widen a vavr sequence?
280 Views Asked by Noel Yap At
1
Seq.narrow()
does exactly that: going from a sequence of some typeT
to a sequence of a supertypeS
of that typeT
.The following example compiles:
This works because vavr collections are immutable, so when you have a
Seq<T>
you can be sure that all values in the sequence are also values of typeS
. Since you cannot change a vavr collection, narrowing a reference toSeq<T>
toSeq<S>
is always safe (T
being a subtype ofS
), since you can never change the originalSeq<T>
by adding a value of typeS
into it. That would violate the type safety of the originalSeq<T>
, as now it would contain an element which is notT
. Note that this cannot be guaranteed for mutable collections, so all such narrowing of mutable collections would be inherently unsafe.