@@ -6,6 +6,14 @@ import scala.reflect.*
66
77import Macro .*
88
9+ // scala3 lambda generated during derivation reference outer scope
10+ // This fails the typeclass serialization if the outer scope is not serializable
11+ // workaround with this with a serializable fuction
12+ private trait SerializableFunction0 [+ R ] extends Function0 [R ] with Serializable :
13+ def apply (): R
14+ private trait SerializableFunction1 [- T1 , + R ] extends Function1 [T1 , R ] with Serializable :
15+ def apply (v1 : T1 ): R
16+
917object CaseClassDerivation :
1018 inline def fromMirror [Typeclass [_], A ](
1119 product : Mirror .ProductOf [A ]
@@ -97,12 +105,17 @@ object CaseClassDerivation:
97105 case _ : (EmptyTuple , EmptyTuple ) =>
98106 Nil
99107 case _ : ((l *: ltail), (p *: ptail)) =>
100- def unsafeCast (any : Any ) = Option .when(any == null || (any : @ unchecked).isInstanceOf [p])(any.asInstanceOf [p])
101108 val label = constValue[l].asInstanceOf [String ]
109+ val tc = new SerializableFunction0 [Typeclass [p]]:
110+ override def apply (): Typeclass [p] = summonInline[Typeclass [p]]
111+
112+ val d = new SerializableFunction0 [Option [p]]:
113+ private def unsafeCast (any : Any ) = Option .when(any == null || (any : @ unchecked).isInstanceOf [p])(any.asInstanceOf [p])
114+ override def apply (): Option [p] = defaults.get(label).flatten.flatMap(d => unsafeCast(d.apply))
102115 paramFromMaps[Typeclass , A , p](
103116 label,
104- CallByNeed (summonInline[ Typeclass [p]] ),
105- CallByNeed .withValueEvaluator(defaults.get(label).flatten.flatMap(d => unsafeCast(d.apply)) ),
117+ CallByNeed .createLazy(tc ),
118+ CallByNeed .createValueEvaluator(d ),
106119 repeated,
107120 annotations,
108121 inheritedAnnotations,
@@ -172,7 +185,16 @@ trait SealedTraitDerivation:
172185 mm.asInstanceOf [m.type ],
173186 0
174187 )
175- case _ =>
188+ case _ => {
189+ val tc = new SerializableFunction0 [Typeclass [s]]:
190+ override def apply (): Typeclass [s] = summonFrom {
191+ case tc : Typeclass [`s`] => tc
192+ case _ => deriveSubtype(summonInline[Mirror .Of [s]])
193+ }
194+ val isType = new SerializableFunction1 [A , Boolean ]:
195+ override def apply (a : A ): Boolean = a.isInstanceOf [s & A ]
196+ val asType = new SerializableFunction1 [A , s & A ]:
197+ override def apply (a : A ): s & A = a.asInstanceOf [s & A ]
176198 List (
177199 new SealedTrait .Subtype [Typeclass , A , s](
178200 typeInfo[s],
@@ -181,14 +203,12 @@ trait SealedTraitDerivation:
181203 IArray .from(paramTypeAnns[A ]),
182204 isObject[s],
183205 idx,
184- CallByNeed (summonFrom {
185- case tc : Typeclass [`s`] => tc
186- case _ => deriveSubtype(summonInline[Mirror .Of [s]])
187- }),
188- x => x.isInstanceOf [s & A ],
189- _.asInstanceOf [s & A ]
206+ CallByNeed .createLazy(tc),
207+ isType,
208+ asType
190209 )
191210 )
211+ }
192212 }
193213 (sub ::: subtypesFromMirror[A , tail](m, idx + 1 )).distinctBy(_.typeInfo).sortBy(_.typeInfo.full)
194214end SealedTraitDerivation
0 commit comments