簡體   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