Skip to content

Overload that differs only in parameter type is mistaken as override, crashes with a ClassCastException at runtime #12828

Closed
@julienrf

Description

@julienrf

Compiler version

3.0.1-RC1

Minimized code

trait Foo[A]:
  def foo(x: A): Unit

trait Bar[A] extends Foo[A]:
  def foo(x: A & String): Unit = println(x.toUpperCase)

object Baz extends Bar[Int]

@main def run() = Baz.foo(42)

Output

The code compiles, but fails at run-time:

java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
at Baz$.foo(main.scala:7)

Expectation

The code should not compile. It should produce the following error:

object creation impossible, since def foo(x: A): Unit in trait Foo is not defined
(Note that
parameter A in def foo(x: A): Unit in trait Foo does not match
parameter A & String in def foo(x: A & String): Unit in trait Bar
type A & String is a subtype of trait A, but method parameter types must match exactly.)

Note: adding the override keyword raises a compile-time error:

trait Foo[A]:
  def foo(x: A): Unit

trait Bar[A] extends Foo[A]:
  override def foo(x: A & String): Unit = println(x.toUpperCase)
//                    ^^^^^^^^^^
// method foo has a different signature than the overridden declaration

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions