繁体   English   中英

在 Scala 3 中打印 MirroredElemTypes

[英]Printing MirroredElemTypes in Scala 3

我正在尝试修改标准示例以打印具有类型的值。 我被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]]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM