Skip to content

Commit 56152b7

Browse files
Don't generate apply methods if constructor is explicitly private (#10)
1 parent 8e903e7 commit 56152b7

File tree

2 files changed

+35
-20
lines changed

2 files changed

+35
-20
lines changed

src/main/scala/dataclass/Macros.scala

Lines changed: 23 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -325,26 +325,29 @@ private[dataclass] class Macros(val c: Context) extends ImplTransformers {
325325
val q"$mmods object $mname extends { ..$mearlydefns } with ..$mparents { $mself => ..$mstats }" =
326326
mdef
327327

328-
val applyMethods = splits.map { idx =>
329-
val (a, b) = paramss.head.splitAt(idx)
330-
val a0 = a.map {
331-
case ValDef(mods, name, tpt, _) =>
332-
q"$name: $tpt"
333-
}
334-
// Weirdly enough, things compile fine without this check (resulting in empty trees hanging around)
335-
b.foreach { p =>
336-
if (p.rhs.isEmpty)
337-
c.abort(
338-
p.pos,
339-
s"Found parameter with no default value ${p.name} after @since annotation"
340-
)
341-
}
342-
val a1 = a0 :: paramss.tail
343-
q""" def apply[..$tparams](...$a1): $tpname[..$tparamsRef] = new $tpname[..$tparamsRef](...${(a
344-
.map(p => q"${p.name}") ++ b.map(_.rhs)) :: paramss.tail.map(
345-
_.map(p => q"${p.name}")
346-
)})"""
347-
}
328+
val applyMethods =
329+
if (ctorMods.hasFlag(Flag.PRIVATE)) Nil
330+
else
331+
splits.map { idx =>
332+
val (a, b) = paramss.head.splitAt(idx)
333+
val a0 = a.map {
334+
case ValDef(mods, name, tpt, _) =>
335+
q"$name: $tpt"
336+
}
337+
// Weirdly enough, things compile fine without this check (resulting in empty trees hanging around)
338+
b.foreach { p =>
339+
if (p.rhs.isEmpty)
340+
c.abort(
341+
p.pos,
342+
s"Found parameter with no default value ${p.name} after @since annotation"
343+
)
344+
}
345+
val a1 = a0 :: paramss.tail
346+
q""" def apply[..$tparams](...$a1): $tpname[..$tparamsRef] = new $tpname[..$tparamsRef](...${(a
347+
.map(p => q"${p.name}") ++ b.map(_.rhs)) :: paramss.tail.map(
348+
_.map(p => q"${p.name}")
349+
)})"""
350+
}
348351

349352
val mdef0 =
350353
q"$mmods object $mname extends { ..$mearlydefns } with ..$mparents { $mself => ..$mstats; ..$applyMethods }"

src/test/scala/dataclass/OneFieldTests.scala

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,18 @@ object OneFieldTests extends TestSuite {
184184
assert(bar != bar0)
185185
}
186186
}
187+
188+
"no apply if explicitly private constructor" - {
189+
@data class Bar private (path: String)
190+
object Bar {
191+
def apply(path: String): Bar =
192+
new Bar(path.stripSuffix("/"))
193+
}
194+
195+
val bar = Bar("foo/1")
196+
val bar0 = Bar("foo/1/")
197+
assert(bar == bar0)
198+
}
187199
}
188200
}
189201
}

0 commit comments

Comments
 (0)