Immutability, part 2.5: Adding covariance to the immutable stack – SLaks.Blog
Immutability, part 2.5: Adding covariance to the immutable stack
Posted on Friday, June 28, 2013Last time, I showed how to create a simple immutable stack. However, this stack is not covariant. Ideally, we should be able (for example) to implicitly convert IStack<string>
to IStack<object>
.
Most collection types cannot be co-variant. Had List<string>
been convertible to List<object>
, you would then be able to add an int
(or any other type) to the converted List<object>
, even though it can't fit in List<string>
(which the casted instance actually is). To be precise, covariance is only type-safe for immutable types.
Since our Stack<T>
class is immutable, we should be able to simply change it to public interface Stack<out T>
and get co-variance instantly.
In practice, it's not so simple. Even though the class is immutable, it still has a method that takes T
as a parameter (namely, Push(T)
). Even though the method doesn't mutate anything, it still wouldn't be type safe:
Read full article from Immutability, part 2.5: Adding covariance to the immutable stack – SLaks.Blog
No comments:
Post a Comment