Skip to content

Opaque type alias evidence #17798

@cchantep

Description

@cchantep

It would nice that opaque type aliases were given evidence at typelevel. e.g.

def funThatExceptOpaqueTypeAlias[T: OpaqueAlias] = println("ok")

opaque type Foo = Double

funThatExceptOpaqueTypeAlias[Foo] // ok

funThatExceptOpaqueTypeAlias[Double] // do not compile

Something as below can be designed.

sealed trait OpaqueAlias[T] {}

object OpaqueAlias:
  import scala.quoted.{ Expr, Quotes, Type }

  inline given materialized[T]: OpaqueAlias[T] = ${ impl[T] }

  private def impl[T: Type](using q: Quotes): Expr[OpaqueAlias[T]] = {
    import q.reflect.*

    TypeRepr.of[T] match {
      case ref: TypeRef if ref.isOpaqueAlias =>
        ref.asType match {
          case tpe @ '[t] => '{ new OpaqueAlias[T] {} }
        }

      case tpr =>
        report.errorAndAbort(s"${tpr.show} is not an opaque alias")
    }
  }

end OpaqueAlias

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions