1

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

4

1 回答 1

1

要检查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]]]
于 2021-10-10T17:32:50.977 回答