Derive typeclass instances for opaque types in Scala 3
Asked Answered
B

1

8

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
Brassbound answered 6/9, 2022 at 16:27 Comment(1)
The closest I know would be using monix-newtype: github.com/monix/newtypesFrankfurter
T
5

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.

Tiernan answered 7/9, 2022 at 9:58 Comment(1)
Thanks for your answer. Something along the lines of Haskell's deriving via mechanism (or even a simplified version of it for common use cases) was exactly what I had in mind when asking this question. I totally agree with you that the motivation behind using opaque types is to distinguish them from the underlying one (for example, I don't want the Id type in my original question to have an instance of the Num typeclass), however when constructing instances for my new type it would come handy to have (local to definition site) a mechanism to piggy back on the underlying typeBrassbound

© 2022 - 2024 — McMap. All rights reserved.