0

When I compile this code, I get ambiguous reference error for method m1. Can someone tell me why?

object MyClass {
    trait T {
        def m1(str: String): Unit = println(str)
        def m1: Unit = {
            println("m1")
            m1("from:m1")
        }
    }
    class C extends T {
        override def m1(str: String): Unit = println(str+"1")
    }

    def main(args: Array[String]): Unit = {
        val c = new C()
        c.m1
    }
}

Error

gianluca aguzzi
  • 1,734
  • 1
  • 10
  • 22
ash164
  • 231
  • 3
  • 9
  • 3
    There are some questions related to this problems, for example [here](https://stackoverflow.com/questions/7721598/scala-ambiguous-reference-to-overloaded-definition-best-disambiguation) and [here](https://stackoverflow.com/questions/7498677/why-is-this-reference-ambiguous). I hope that these questions can you a little bit. – gianluca aguzzi Aug 25 '21 at 09:59
  • 3
    Since the second method is doing a side-effect the style guide says that it should be defined as `def m1(): Unit = {` and thus the call site must be `c.m1()` and that should fix the ambiguity problem. – Luis Miguel Mejía Suárez Aug 25 '21 at 12:39
  • @LuisMiguelMejíaSuárez Thanks. You are right about it. – ash164 Aug 27 '21 at 03:54

1 Answers1

2

When you call C.m1 in main you don't include parentheses. The compiler doesn't know if you are intentionally calling the arity-0 method, or were intending to call the arity-1 method using infix notation, eg c.m1 "hello".

Replacing c.m1 with c.m1() will compile.

Jarrod Baker
  • 1,150
  • 8
  • 13