Skip to content

Commit ad675af

Browse files
committed
Generate toString only for synthetic companions of case classes
Don't generate a toString method if the companion is explicitly given. This matches Scala 2's behavior. Fixes #16879
1 parent 3d251d6 commit ad675af

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

compiler/src/dotty/tools/dotc/typer/Namer.scala

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -541,7 +541,11 @@ class Namer { typer: Typer =>
541541
res = cpy.TypeDef(modCls)(
542542
rhs = cpy.Template(modTempl)(
543543
derived = if (fromTempl.derived.nonEmpty) fromTempl.derived else modTempl.derived,
544-
body = fromTempl.body ++ modTempl.body))
544+
body = fromTempl.body.filter {
545+
case stat: DefDef => stat.name != nme.toString_
546+
// toString should only be generated if explicit companion is missing
547+
case _ => true
548+
} ++ modTempl.body))
545549
if (fromTempl.derived.nonEmpty) {
546550
if (modTempl.derived.nonEmpty)
547551
report.error(em"a class and its companion cannot both have `derives` clauses", mdef.srcPos)

tests/run/i16879.scala

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
trait Companion:
2+
final override def toString: String = "Companion"
3+
4+
case class Example(value: Int)
5+
object Example extends Companion
6+
7+
case class C()
8+
object C:
9+
override def toString = "CC"
10+
11+
case class D()
12+
13+
@main def Test =
14+
assert(Example.toString == "Companion")
15+
assert(C.toString == "CC")
16+
assert(D.toString == "D")

0 commit comments

Comments
 (0)