-
Notifications
You must be signed in to change notification settings - Fork 1.1k
TypeTest for opaque type with wildcard argument #20430
-
A TypeTest can be used with opaque type aliases or abstract type members to enable safe pattern matching. We can write a pattern match on an opaque type with a wildcard argument:
def bar(o: Any) = o match case b: Foo.Opaque[?] => println("match opaque wildcard") case _ => println("NO match opaque wildcard")
Unfortunately, applying a wildcard type to an opaque type is illegal in all other places (in contrast to classes with type parameters, where you can legally apply wildcards for all parameters), so we can not actually provide a TypeTest specifically for a wildcard pattern match:
object Foo { opaque type Opaque[T] = Option[T] def newOpaque[T]: Opaque[T] = Option.empty[T] // ERROR: unreducible application of higher-kinded type com.tschuchort.Foo.Opaque to wildcard arguments given TypeTest[Any, Opaque[?]] with { override def unapply(x: Opaque[?]): Option[x.type & Opaque[?]] = ??? } }
It seems that the compiler will always translate the wildcard into a type _ >: Nothing <: Any regardless of the expected kind of the type parameter. The following TypeTest would be chosen here, but will cause a compiler crash (see #20429):
given [T]: TypeTest[Any, Opaque[T]] with { override def unapply(x: Opaque[T]): Option[x.type & Opaque[T]] = ??? }
For higher kinded opaque type aliases, no TypeTest would be chosen because the wildcard is of an illegal kind in that position (also see #20429).
I think it would be very useful to be able to provide a TypeTest for types with wildcard arguments. My proposal is to translate the wildcard to the appropriately kinded least specific upper bound (Any, [_] =>> Any, [_[_]] =>> Any, etc.) when looking for a TypeTest. This should be pretty easy to implement and would also automatically fix #20429.
Beta Was this translation helpful? Give feedback.
All reactions
-
👍 1