A trick for invariant generics in Sorbet – Jake Zimmerman
07-Jun-2024 492
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 #trick #invariant #generics #Sorbet #Zimmerman https://rubyonrails.ba/link/a-trick-for-invariant-generics-in-sorbet-jake-zimmerman