scalatypeclassscala-3derivingderivingvia

Derive typeclass instances for opaque types in Scala 3


Is there a way in Scala 3 to use derives keyword in combination with opaque type aliases? It would be nice to have a boilerplate-free way to provide a typeclass instance to a given opaque type alias by automatically rely on the instance of the same type class for the underlying type (if any).

Would be nice to have the possibility of expressing something like

opaque type Id = Int 
object Id:
  given Show[Id] = Show.intShow

for some hypothetical typeclass Show, as

opaque type Id = Int derives Show

Solution

  • You can see in syntax.md that there is no such construct at the moment.

    Also, even if such syntax was available, I'm not sure if this should be the default behavior. The motivation behind using opaque types is to distinguish the new type from the underlying one. Though I get why it would be useful to have, just not as a default.

    Maybe something similar to Haskell's deriving via might be a good addition here. It might be a good candidate for a SIP.