您可以创建一个transparent 宏,该宏返回一个structural type,以生成您希望的任何vals 和defs 的类型。
这是一个例子;方法 props,当使用 Product 类型调用时,创建一个对象,其第一个 Product 元素名称为字符串 val。
case class User(firstName: String, age: Int)
// has the type of Props { val firstName: String }
val userProps = props[User]
println(userProps.firstName) // prints "prop for firstName"
println(userProps.lastName) // compile error
还有实现,虽然有点棘手但还不错:
import scala.compiletime.*
import scala.quoted.*
import scala.deriving.Mirror
class Props extends Selectable:
def selectDynamic(name: String): Any =
"prop for " + name
transparent inline def props[T] =
${ propsImpl[T] }
private def propsImpl[T: Type](using Quotes): Expr[Any] =
import quotes.reflect.*
Expr.summon[Mirror.ProductOf[T]].get match
case '{ $m: Mirror.ProductOf[T] {type MirroredElemLabels = mels; type MirroredElemTypes = mets } } =>
Type.of[mels] match
case '[mel *: melTail] =>
val label = Type.valueOfConstant[mel].get.toString
Refinement(TypeRepr.of[Props], label, TypeRepr.of[String]).asType match
case '[tpe] =>
val res = '{
val p = Props()
p.asInstanceOf[tpe]
}
println(res.show)
res
使用递归,您可以优化 Refinement(因为 Refinement <: typerepr>
话虽如此,使用transparent inline 甚至Scala 2 宏注释来生成新类型使得IDE 很难支持自动完成。所以如果可能的话,我推荐使用标准的Typeclass derivation。
您甚至可以推导出标准特征的默认行为:
trait SpringDataRepository[E, Id]:
def findAll(): Seq[E]
trait DerivedSpringDataRepository[E: Mirror.ProductOf, Id]:
def findAll(): Seq[E] = findAllDefault[E, Id]()
private inline def findAllDefault[E, Id](using m: Mirror.ProductOf[E]): Seq[E] =
findAllDefaultImpl[E, m.MirroredLabel, m.MirroredElemLabels]()
private inline def findAllDefaultImpl[E, Ml, Mels](columns: ArrayBuffer[String] = ArrayBuffer()): Seq[E] =
inline erasedValue[Mels] match
case _: EmptyTuple =>
// base case
println("executing.. select " + columns.mkString(", ") + " from " + constValue[Ml])
Seq.empty[E]
case _: (mel *: melTail) =>
findAllDefaultImpl[E, Ml, melTail](columns += constValue[mel].toString)
然后,用户所要做的就是用他们的产品类型扩展DerivedSpringDataRepository:
case class User(id: Int, first: String, last: String)
class UserRepo extends DerivedSpringDataRepository[User, Int]
val userRepo = UserRepo()
userRepo.findAll() // prints "executing.. select id, first, last from User"