Skip to content

Commit

Permalink
Merge pull request #1239 from joroKr21/defaults
Browse files Browse the repository at this point in the history
Merge pull request #1238 from joroKr21/default-access
  • Loading branch information
joroKr21 authored Feb 11, 2022
2 parents 2137969 + a12538b commit 2aebbc1
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 9 deletions.
21 changes: 12 additions & 9 deletions core/src/main/scala/shapeless/default.scala
Original file line number Diff line number Diff line change
Expand Up @@ -240,15 +240,18 @@ class DefaultMacros(val c: whitebox.Context) extends CaseClassMacros {
alt => alt.isMethod && hasDefaultParams(alt.asMethod)
}

def defaultsFor(fields: List[(TermName, Type)]) = for {
((_, argTpe), i) <- fields.zipWithIndex
default = tpe.companion.member(TermName(s"apply$$default$$${i + 1}")) orElse
altCompanion.member(TermName(s"$$lessinit$$greater$$default$$${i + 1}"))
} yield if (default.isTerm) {
val defaultTpe = appliedType(someTpe, devarargify(argTpe))
val defaultVal = some(q"$companion.$default")
(defaultTpe, defaultVal)
} else (noneTpe, none)
def defaultsFor(fields: List[(TermName, Type)]) = {
lazy val enclosing = ownerChain(c.internal.enclosingOwner)
for (((_, argTpe), i) <- fields.zipWithIndex) yield {
val default = tpe.companion.member(TermName(s"apply$$default$$${i + 1}")) orElse
altCompanion.member(TermName(s"$$lessinit$$greater$$default$$${i + 1}"))
if (default.isTerm) {
val owner = default.owner
val qualifier = if (!owner.isStatic && enclosing.contains(owner)) This(owner) else companion
(appliedType(someTpe, devarargify(argTpe)), some(q"$qualifier.$default"))
} else (noneTpe, none)
}
}

def mkDefault(defaults: List[(Type, Tree)]) = {
val (types, values) = defaults.unzip
Expand Down
10 changes: 10 additions & 0 deletions core/src/test/scala/shapeless/default.scala
Original file line number Diff line number Diff line change
Expand Up @@ -240,4 +240,14 @@ class DefaultTests {
}
assert(thrownException, "Expected DefaultRun to be thrown")
}

@Test
def testInCompanion: Unit =
assertEquals(InCompanion.default, Some(9) :: HNil)

// Note: this has to be inside a class, not an object
case class InCompanion(a: Int = 9)
object InCompanion {
val default = Default[InCompanion].apply()
}
}

0 comments on commit 2aebbc1

Please sign in to comment.