A trick for invariant generics in Sorbet – Jake Zimmerman

There’s a neat trick for using generic methods to get around some of the limitations that invariant type members in generic classes carry.The problem I’m trying to solve:Sometimes my generic class (say, Box) needs a type_member (say, Elem) to be invariant, because the type member is used in both input and output positions. For example, maybe this is a generic, mutable container (as contrasted with an immutable, read-only container).… but I still want to allow covariant subtyping in methods that take this generic type as an argument. For example, if I write a method that takes a Box[Numeric], you should be able to call it if you have a Box[Integer]. Normally, the fact that Elem is invariant prevents this.
A trick for invariant generics in Sorbet – Jake Zimmerman #ruby #rubydeveloper #rubyonrails https://www.rubyonrails.ba/single/a-trick-for-invariant-generics-in-sorbet-jake-zimmerman

Nezir Zahirovic

Contractor Ruby On Rails (8+ years) / MCPD .Net / C# / Asp.Net / CSS / SQL / (11 years)

related articles