Hello
I am working on Scala 3 training materials and finding it a bit tricky to teach a simple LinkedList enum without having to introduce variance first.
enum LinkedList[A]:
case Empty
case NonEmpty(a: A, tail: LinkedList[A])
That won’t compile unless I declare A as covariant or explicitly extending LinkedList[Nothing] on the Empty case.
I wonder what Scala instructors do? Shall I go with the extends hack or just introduce covariance at this early stage of the course?
Another option - what I’d do with my 11-year-olds - is to stay focused on the data structure lesson at hand and put off the puzzles of variance for another day. Something like:
enum LinkedList:
case Empty()
case NonEmpty(a: Any, tail: LinkedList)
However, it might be as much to explain “Don’t use Any after September,” as “You need a + here. I’ll explain why in October.”
I actually realized about a week ago that I had this same in PinS 5ed. We added an enums chapter well before we explain covariance, but several unexplained plus signs were lurking quietly in the enum examples. I decided I will leave the plus signs in and add a footnote or callout that says the plus signs means covariance, which will be explained in section X.Y and in short means… Otherwise we’d need to twist our examples into pretzels to avoid covariance, or introduce enums way later than they deserve.