简体   繁体   English

在 Scala 3 中打印 MirroredElemTypes

[英]Printing MirroredElemTypes in Scala 3

I am trying to modify this standard example to print values with the types.我正在尝试修改标准示例以打印具有类型的值。 And I am stuck with p.MirroredElemTypes .我被p.MirroredElemTypes困住了。 I haven't found any API to traverse and stringify types.我还没有找到任何 API 来遍历和字符串化类型。

To check MirroredElemTypes you can just summon要检查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

But if you want to print MirroredElemTypes you can do the following.但是,如果您想打印MirroredElemTypes ,您可以执行以下操作。

For some reason Typeable doesn't work now but in its error message it prints the type出于某种原因, 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

Alternatively you can write a simple macro或者,您可以编写一个简单的宏

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