Skip to content

Commit

Permalink
Generate toString only for synthetic companions of case classes
Browse files Browse the repository at this point in the history
Don't generate a toString method if the companion is explicitly given.
This matches Scala 2's behavior.

Fixes #16879
  • Loading branch information
odersky committed Feb 11, 2023
1 parent 3d251d6 commit ad675af
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
6 changes: 5 additions & 1 deletion compiler/src/dotty/tools/dotc/typer/Namer.scala
Original file line number Diff line number Diff line change
Expand Up @@ -541,7 +541,11 @@ class Namer { typer: Typer =>
res = cpy.TypeDef(modCls)(
rhs = cpy.Template(modTempl)(
derived = if (fromTempl.derived.nonEmpty) fromTempl.derived else modTempl.derived,
body = fromTempl.body ++ modTempl.body))
body = fromTempl.body.filter {
case stat: DefDef => stat.name != nme.toString_
// toString should only be generated if explicit companion is missing
case _ => true
} ++ modTempl.body))
if (fromTempl.derived.nonEmpty) {
if (modTempl.derived.nonEmpty)
report.error(em"a class and its companion cannot both have `derives` clauses", mdef.srcPos)
Expand Down
16 changes: 16 additions & 0 deletions tests/run/i16879.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
trait Companion:
final override def toString: String = "Companion"

case class Example(value: Int)
object Example extends Companion

case class C()
object C:
override def toString = "CC"

case class D()

@main def Test =
assert(Example.toString == "Companion")
assert(C.toString == "CC")
assert(D.toString == "D")

0 comments on commit ad675af

Please sign in to comment.