A trick for invariant generics in Sorbet – Jake Zimmerman

07-Jun-2024 530
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.
Use coupon code:

RUBYONRAILS

to get 30% discount on our bundle!
Prepare for your next tech interview with our comprehensive collection of programming interview guides. Covering JavaScript, Ruby on Rails, React, and Python, these highly-rated books offer thousands of essential questions and answers to boost your interview success. Buy our 'Ultimate Job Interview Preparation eBook Bundle' featuring 2200+ questions across multiple languages. Ultimate Job Interview Preparation eBook Bundle