From 3f9ee733ac73f31337433227eb6871efce18981c Mon Sep 17 00:00:00 2001 From: Jon Pretty Date: Sun, 5 Nov 2017 12:06:14 +0100 Subject: Create fewer anonymous PartialFunction classes --- core/src/main/scala/magnolia.scala | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/core/src/main/scala/magnolia.scala b/core/src/main/scala/magnolia.scala index 9c8891e..2d2bbcd 100644 --- a/core/src/main/scala/magnolia.scala +++ b/core/src/main/scala/magnolia.scala @@ -14,11 +14,14 @@ trait Subclass[Tc[_], T] { } object Subclass { - def apply[Tc[_], T, S1 <: T](name: String, tc: => Tc[S1], pf: => PartialFunction[T, S1]) = new Subclass[Tc, T] { + def apply[Tc[_], T, S1 <: T](name: String, tc: => Tc[S1], isType: T => Boolean, asType: T => S1) = new Subclass[Tc, T] { type S = S1 def label: String = name def typeclass: Tc[S] = tc - def cast: PartialFunction[T, S] = pf + def cast: PartialFunction[T, S] = new PartialFunction[T, S] { + def isDefinedAt(t: T) = isType(t) + def apply(t: T): S = asType(t) + } } } @@ -198,13 +201,12 @@ object Magnolia { c.abort(c.enclosingPosition, s"failed to get implicit for type $searchType") } }.map { case (typ, typeclass) => - val pf = q""" - new _root_.scala.PartialFunction[$genericType, $typ] { - def isDefinedAt(t: $genericType): Boolean = t.isInstanceOf[$typ] - def apply(t: $genericType): $typ = t.asInstanceOf[$typ] - }""" - - q"""_root_.magnolia.Subclass[$typeConstructor, $genericType, $typ](${typ.typeSymbol.name.toString}, $typeclass, $pf)""" + q"""_root_.magnolia.Subclass[$typeConstructor, $genericType, $typ]( + ${typ.typeSymbol.name.toString}, + $typeclass, + (t: $genericType) => t.isInstanceOf[$typ], + (t: $genericType) => t.asInstanceOf[$typ] + )""" } Some { -- cgit v1.2.3