Pre-SIP derives clauses for opaque types
I propose two changes to the Scala language:
-
Adding a
derives
clause foropaque
types that will be desugared to a normal call to thederived
method on the typeclass.
e.g.opaque type USD = Int derives Show
will be desugared to
opaque type USD = Int object USD { given Show[USD] = Show.derived[USD] }
I think that this use case might not be very popular, especially since there are no
Mirror
s foropaque
types. But they still can be generated using macros, so it’s the only reasonable thing to keep it consistent with classes. -
Adding a
derives via
clause foropaque
types that will be desugared to a proxy to another types instance.
e.g.opaque type USD = Int derives Show via Int
will be desugared to
opaque type USD = Int object USD { given (using intShow: Show[Int]): Show[USD] = intShow.asInstanceOf[Show[USD]] // obviously try to avoid the `asInstanceOf` if possible }
I think that this might be by far the most useful case, since it is often that case that the instance for the underlying type can be used for the
opaque
type.When it comes to syntax, the
via
clause will have to be used per typeclass, so the following two declarations will NOT be equivalent.opaque type USD = Int derives Eq, Show via Int // and opaque type USD = Int derives Eq via Int, Show via Int
Some variations
The downside of this syntax is that it introduces a new keyword. And although via
shouldn’t be a popular symbol name, this change won’t nearly be common enough to justify introducing a new keyword.
All syntax option to consider:
derives Show via Int
derives Show using Int
derives Show as Int
Another notion to consider is the desugaring of derives via
clauses. Two possibilities:
-
given (using intShow: Show[Int]): Show[USD] = intShow.asInstanceOf[Show[USD]]
-
given Show[USD] = Show.derived[Int].asInstanceOf[Show[USD]]
Any feedback greatly appreciated.