Skip to content

Commit

Permalink
Fix when for parameterized types on Scala 2
Browse files Browse the repository at this point in the history
It already works on Scala 3.
Although in the general case it's eliminated by erasure,
we would get a warning because it's implemented as a pattern match.
  • Loading branch information
joroKr21 committed May 10, 2023
1 parent 55a0337 commit de9bfc3
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ object QuicklensMacros {

sealed trait PathElement
case class TermPathElement(term: c.TermName, access: PathAccess, xargs: c.Tree*) extends PathElement
case class SubtypePathElement(subtype: c.Symbol) extends PathElement
case class SubtypePathElement(subtype: c.Type) extends PathElement
case class FunctorPathElement(functor: c.Tree, method: c.TermName, xargs: c.Tree*) extends PathElement

/** Determine if the `.copy` method should be applied directly or through a match across all subclasses (for sealed
Expand Down Expand Up @@ -168,7 +168,7 @@ object QuicklensMacros {
val access = determinePathAccess(parent.tpe.typeSymbol)
collectPathElements(parent, TermPathElement(child, access) :: acc)
case q"$tpname[..$_]($parent).when[$tp]" if typeSupported(tpname) =>
collectPathElements(parent, SubtypePathElement(tp.tpe.typeSymbol) :: acc)
collectPathElements(parent, SubtypePathElement(tp.tpe) :: acc)
case q"$parent.$method(..$xargs)" if methodSupported(method) =>
collectPathElements(parent, TermPathElement(method, DirectPathAccess, xargs: _*) :: acc)
case q"$tpname[..$_]($t)($f)" if typeSupported(tpname) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,14 @@ object ModifyWhenTestData {

val zoo = Zoo(List(dog, cat))
val olderZoo = Zoo(List(olderDog, olderCat))

trait MyOption[+A]
case class MySome[+A](value: A) extends MyOption[A]
case object MyNone extends MyOption[Nothing]

val someDog: MyOption[Dog] = MySome(Dog(4))
val someOlderDog: MyOption[Dog] = MySome(Dog(5))
val noDog: MyOption[Dog] = MyNone
}

class ModifyWhenTest extends AnyFlatSpec with Matchers {
Expand All @@ -42,4 +50,12 @@ class ModifyWhenTest extends AnyFlatSpec with Matchers {
)
.using(_ + 1) shouldEqual olderZoo
}

it should "modify a field in a subtypes (parameterized)" in {
someDog.modify(_.when[MySome[Dog]].value.age).using(_ + 1) shouldEqual someOlderDog
}

it should "ignore subtypes other than the selected one (parameterized)" in {
noDog.modify(_.when[MySome[Dog]].value.age).using(_ + 1) shouldEqual MyNone
}
}

0 comments on commit de9bfc3

Please sign in to comment.