File tree 2 files changed +42
-0
lines changed
2 files changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ import scala .deriving ._
2
+ import scala .quoted ._
3
+ import scala .quoted .matching ._
4
+ import scala .compiletime .{erasedValue , summonFrom , constValue }
5
+
6
+ object Macro {
7
+ case class Person (name : String , age : Int )
8
+
9
+ // Summon a mirror for a particular type
10
+ inline def summonMirror [T ]: Option [Mirror .Of [T ]] =
11
+ summonFrom {
12
+ case given m : Mirror .Of [T ] => Some (m)
13
+ case _ => None
14
+ }
15
+
16
+ // Get fields from a mirror:
17
+ inline def mirrorFields [Fields <: Tuple ]: List [String ] =
18
+ inline erasedValue[Fields ] match {
19
+ case _ : (field *: fields) => constValue[field].toString :: mirrorFields[fields]
20
+ case _ => Nil
21
+ }
22
+
23
+ inline def usingSummonFrom [T ](value : => T ): String =
24
+ $ { usingSummonFromImpl(' value , summonMirror[T ]) }
25
+
26
+ def usingSummonFromImpl [T : Type ](value : Expr [T ], m : Option [Mirror .Of [T ]])(given qctx : QuoteContext ): Expr [String ] = {
27
+ import qctx .tasty .{_ , given }
28
+ val theMirror = m match { case Some (mirror) => mirror }
29
+
30
+ theMirror match {
31
+ case m : Mirror .ProductOf [T ] => println(" it's a product: " + mirrorFields[m.MirroredElemLabels ])
32
+ }
33
+
34
+ ' { " Doesn't matter" }
35
+ }
36
+ }
Original file line number Diff line number Diff line change
1
+ import Macro ._
2
+
3
+ @ main def Test () = {
4
+ val list = usingSummonFrom[Person ](Person (" Test" , 23 ))
5
+ println(list)
6
+ }
You can’t perform that action at this time.
0 commit comments