scala - 类型类派生访问默认值

标签 scala typeclass scala-macros scala-3 generic-derivation

使用镜像在 Scala 3 中执行类型类派生时,是否有一种干净的方法来访问案例类字段的默认值?例如:

case class Foo(s: String = "bar", i: Int, d: Double = Math.PI)
Mirror.Product.MirroredElemLabels将设置为 ("s", "i", "d") .有没有类似的东西:(Some["bar"], None, Some[3.141592653589793]) ?
如果不能,这可以使用宏来实现吗?我可以同时使用镜像和宏来派生类型类实例吗?

最佳答案

您必须编写一个宏,使用名为 <init>$default$1 的方法。 , <init>$default$2 , ... 在伴生对象中

import scala.quoted.*

inline def printDefaults[T]: Unit = ${printDefaultsImpl[T]}

def printDefaultsImpl[T](using Quotes, Type[T]): Expr[Unit] = {
  import quotes.reflect.*

  (1 to 3).map(i =>
    TypeRepr.of[T].typeSymbol
      .companionClass
      .declaredMethod(s"$$lessinit$$greater$$default$$$i")
      .headOption
      .flatMap(_.tree.asInstanceOf[DefDef].rhs)
  ).foreach(println)

 '{()}
}

printDefaults[Foo]
//Some(Literal(Constant(bar)))
//None
//Some(Select(Ident(Math),PI))
镜像和宏可以一起工作:
import scala.quoted.*
import scala.deriving.*

trait Default[T] {
  type Out <: Tuple
  def defaults: Out
}

object Default {
  transparent inline given mkDefault[T](using 
    m: Mirror.ProductOf[T], 
    s: ValueOf[Tuple.Size[m.MirroredElemTypes]]
  ): Default[T] =
    new Default[T] {
      type Out = Tuple.Map[m.MirroredElemTypes, Option]
      def defaults = getDefaults[T](s.value).asInstanceOf[Out]
    }

  inline def getDefaults[T](inline s: Int): Tuple = ${getDefaultsImpl[T]('s)}

  def getDefaultsImpl[T](s: Expr[Int])(using Quotes, Type[T]): Expr[Tuple] = {
    import quotes.reflect.*

    val n = s.asTerm.underlying.asInstanceOf[Literal].constant.value.asInstanceOf[Int]

    val terms: List[Option[Term]] =
      (1 to n).toList.map(i =>
        TypeRepr.of[T].typeSymbol
          .companionClass
          .declaredMethod(s"$$lessinit$$greater$$default$$$i")
          .headOption
          .flatMap(_.tree.asInstanceOf[DefDef].rhs)
      )

    def exprOfOption[T](oet: Option[Expr[T]])(using Type[T], Quotes): Expr[Option[T]] = oet match {
      case None => Expr(None)
      case Some(et) => '{Some($et)}
    }

    val exprs: List[Option[Expr[Any]]] = terms.map(_.map(_.asExprOf[Any]))
    val exprs1: List[Expr[Option[Any]]] = exprs.map(exprOfOption)
    Expr.ofTupleFromSeq(exprs1)
  }
}
用法:
val d = summon[Default[Foo]]
summon[d.Out =:= (Option[String], Option[Int], Option[Double])] // compiles
d.defaults // (Some(bar),None,Some(3.141592653589793))

关于scala - 类型类派生访问默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68421043/

相关文章:

haskell - 默认方法中对幻像类型的类约束的编译错误

haskell - 为什么 ghc 不能在这个 Category 产品上匹配这些类型?

scala - 如何对 Scala (2.12) 宏使用泛型?

scala - 记录 Scala 2.10 宏

scala - Scala 3 宏中的显式类型转换

scala - 我可以从 Scala 中的父类(super class)继承访问修饰符吗?

scala - 为什么我得到 "pattern type is incompatible with expected type"?

scala - 为什么Scala中独立代码块的执行时间依赖于执行顺序?

scala - 运行Scala脚本从Hive获取数据时,权限被拒绝?

haskell - IncoherentInstances 如何工作?