An opaque type and its underlying type have exactly the same representation, so it should be possible to opt to directly reuse delegates for the underlying as delegates for the opaque type. This is pretty much the gist of Andres Loh's Deriving Via paper.
Ideally we'd be able to write something like,
trait Monad[T]
class Foo
object Foo {
delegate for Monad[Foo]
}
opaque type Bar = Foo
object Bar {
delegate for Monad[Bar] = the[Monad[Foo]]
}
object Test {
val mf = the[Monad[Foo]]
val mb = the[Monad[Bar]]
}
But this doesn't work currently, at least in part because recent changes to opaque types mean they no longer have an implicit scope of their own. The closest I think we can get right now is something like,
trait Monad[T]
class Foo
object Foo {
delegate for Monad[Foo]
}
opaque type Bar = Foo
delegate for Monad[Bar] = the[Monad[Foo]].asInstanceOf
object Test {
val mf = the[Monad[Foo]]
val mb = the[Monad[Bar]]
}
which has an ugly (and surely unnecessary?) cast and an untidy top-level delegate definition.
Can we do any better?
Again, super quick comment (sorry for butting in without a lot of context, just had a quick discussion with Miles).
It seems a bit counterintuitive that opaque types won't have a companion object and therefore a convenient implicit scope of their own, given that one of the primary ways to add semantics to them is via typeclass instances.
Since the surrounding object still forms an implicit scope, is there any problem with moving the type inside the object?
trait Monad[T]
class Foo
object Foo {
delegate for Monad[Foo]
}
object Bar {
opaque type Bar = Foo
delegate for Monad[Bar] = the[Monad[Foo]]
}
object Test {
import Bar.Bar
val mf = the[Monad[Foo]]
val mb = the[Monad[Bar]]
}
We agreed that we should bring companion objects for opaque types back, as far as implicit scope is concerned.
nice :)
@AleksanderBG seeing as type aliases can be top level, you can type alias the opaque alias and avoid the import... :-P
Or actually, you can export it (possibly pending https://github.com/lampepfl/dotty/pull/6729 ?).
Most helpful comment
We agreed that we should bring companion objects for opaque types back, as far as implicit scope is concerned.