diff --git a/compiler/src/dotty/tools/dotc/typer/Namer.scala b/compiler/src/dotty/tools/dotc/typer/Namer.scala index 6f85efb0fc8a..cab5dc273f4b 100644 --- a/compiler/src/dotty/tools/dotc/typer/Namer.scala +++ b/compiler/src/dotty/tools/dotc/typer/Namer.scala @@ -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) diff --git a/tests/run/i16879.scala b/tests/run/i16879.scala new file mode 100644 index 000000000000..c01b8cb1ed89 --- /dev/null +++ b/tests/run/i16879.scala @@ -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")