在 Scala 3 中打印 MirroredElemTypes

Printing MirroredElemTypes in Scala 3

我正在尝试修改 this 标准示例以打印带有类型的值。 我坚持 p.MirroredElemTypes。我还没有找到任何 API 来遍历和字符串化类型。

检查MirroredElemTypes你可以召唤

import scala.deriving.Mirror

case class A(i: Int, s: String, b: Boolean)

val m = summon[Mirror.Of[A]]
summon[m.MirroredElemTypes =:= (Int, String, Boolean)] // compiles

但是如果你想打印 MirroredElemTypes 你可以执行以下操作。

出于某种原因,Typeable 现在无法正常工作,但在其错误消息中打印了类型

// scalaVersion := "3.0.2"
// libraryDependencies += "org.typelevel" %% "shapeless3-typeable" % "3.0.3"
import shapeless3.typeable.Typeable

summon[Typeable[m.MirroredElemTypes]].describe
// Typeable for sum type scala.*:[scala.Int, scala.*:[scala.Predef.String, scala.*:[scala.Boolean, scala.Tuple$package.EmptyTuple]]] with no Mirror

或者您可以编写一个简单的宏

import scala.quoted.*

inline def describe[A]: String = ${describeImpl[A]}

def describeImpl[T: Type](using Quotes): Expr[String] = {
  import quotes.reflect.*
  Literal(StringConstant(TypeRepr.of[T].dealias.show)).asExprOf[String]
}

// in a different file
describe[m.MirroredElemTypes]
// scala.*:[scala.Int, scala.*:[scala.Predef.String, scala.*:[scala.Boolean, scala.Tuple$package.EmptyTuple]]]