Parameterised given alias

This one is out of curiosity, as I was trying something out…

Essentially I was looking for what one used to do with implicit def .. in Scala 2.*, where the function took an implicit parameter. The goal being to lift an implicit of one type to being an implicit of another with a one-liner expression that formed the method body. For example, using Eq.by with some mapping function to morph an Eq[X] to some Eq[Wrapped[X]].

I’m aware that Scala 3 has given alias syntax, which seems to be the analogue of implicit val .....

Is there a generic variant of this?

I can write this out in longhand as a generic given ... with, but would prefer to just have the equivalent of:

implicit def liftEqToWrapped[X]
     (implicit val unlifted: Eq[X]): Eq[Wrapped[X]] = 
    Eq.by[Wrapped[X], X](_.extract)

(This may not compile as I’m thinking directly into the Internet, but you get the idea.)

The reason why I’m merely curious is that a) I can get away with freezing the type X and thus can use a monomorphic given and b) I gather there is auto-typeclass derivation for Eq.

I am not sure if I understood the question, but isn’t this simply

given [X](using unlifted Eq[X]): Eq[Wrapped[X]] = Eq.by[Wrapped[X], X](_.extract)

You can add an explicit name if you want.

1 Like

Got it, for some reason it didn’t compile when I first tried it:

given [Item:Eq] : Eq[Wrapped[Item]] = ???

@BalmungSan You beat me to it, yes it is exactly that. Thanks!

2 Likes

Aha - I’d generalised the wrong monomorphic syntax, like that:

given [Item: Eq] Eq[Wrapped[Item]] = ???
              //^ Whoops, no colon.

Just in case anyone else falls into that trap.

3 Likes