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

3
  • 3
    There are some questions related to this problems, for example here and here. I hope that these questions can you a little bit. Commented Aug 25, 2021 at 9: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. Commented Aug 25, 2021 at 12:39
  • @LuisMiguelMejíaSuárez Thanks. You are right about it. Commented Aug 27, 2021 at 3:54

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.