Scala 3 TypeRepr匹配更高级的类型

qrjkbowd  于 2023-04-12  发布在  Scala
关注(0)|答案(2)|浏览(123)

如何在更高级的类型上正确地模式匹配TypeRepr?存在成功匹配类,但当我尝试使用类型时,我得到编译器错误unreducible application of higher-kinded type writetype.Foo to wildcard arguments

import scala.quoted.*

type Foo[X]
class Bar[X]

inline def writeType[T]: String = ${writeTypeImpl[T]}

def writeTypeImpl[T](using Type[T], Quotes): Expr[String] =
  import quotes.reflect.*
  val tpe = TypeRepr.of[T]
  val s = tpe.asType match
    //case '[Foo[?]] => "FooSuccess"
    case '[Bar[?]] => "BarSuccess"
    case _ => "Fail"

  Expr(s)
ubby3x7f

ubby3x7f1#

这就是你需要的答案:
https://docs.scala-lang.org/scala3/guides/migration/incompat-other-changes.html#wildcard-type-argument
必须使用traitabstract classFoo[A],其中是具体类型(或类型参数)

gg58donl

gg58donl2#

@smarter:
这是故意不支持的:我们只允许类类型上的通配符(因为其他任何东西都等同于我们不支持的存在类型)
https://github.com/lampepfl/dotty/issues/9897
https://github.com/lampepfl/dotty/issues/5302
https://users.scala-lang.org/t/solved-unreducible-application-of-higher-kinded-type-to-wildcard-arguments/7257
https://docs.scala-lang.org/scala3/reference/dropped-features/existential-types.html
可以匹配'[Foo[t]]

case '[Foo[t]] => "FooSuccess"
case '[Bar[_]] => "BarSuccess"
case _         => "Fail"

但这并不能像预期的那样处理抽象类型

writeType[Bar[Int]] // BarSuccess
writeType[Bar[?]]   // BarSuccess
writeType[Foo[Int]] // Fail

相关问题