This page is no longer maintained — Please continue to the home page at www.scala-lang.org

ambiguous reference to overloaded definition

2 replies
glurbi
Joined: 2008-09-08,
User offline. Last seen 4 years 4 weeks ago.
Hi,

Let's say I define the following object:

scala> object Foo {
     | def foo(name: String) = {}
     | def foo(name: String)(body: => Unit) = {}
     | }
defined module Foo

Now, I type the following:

scala> Foo.foo("test")
<console>:6: error: ambiguous reference to overloaded definition,
both method foo in object Foo of type (String)(=> Unit)Unit
and  method foo in object Foo of type (String)Unit
match argument types (java.lang.String)
       Foo.foo("test")
           ^

Is there a way to avoid the ambiguity other than defining Foo the following way?

scala> object Foo {
     | def foo(name: String) = {}
     | def foo(name: String, body: => Unit) = {}
     | }

I'm trying to define a DSL and the first definition of Foo would make the language more elegant (at least to my eyes!)

Vincent

glurbi
Joined: 2008-09-08,
User offline. Last seen 4 years 4 weeks ago.
Re: ambiguous reference to overloaded definition
Actually, I might have found a satisfying solution myself, using implicit parameters:

So, instead of

scala> object Foo {
     | def foo(name: String) = {}
     | def foo(name: String)(body: => Unit) = {}
     | }
defined module Foo 

I can define the Foo object like this:

scala> object Foo {
     | def foo(name: String)(implicit body: Unit) = { body }
     | }
defined module Foo

scala> implicit val body: Unit = {}
body: Unit = ()

Then the empty body gets added by the compiler when not specified in the source code.
That makes nested structures of foo elements look more natural:

scala> import Foo._
import Foo._

scala> foo("test") {
     |   foo("a")
     |   foo("b") {
     |     foo("b1")
     |     foo("b2")
     |   }
     | }

It's a pleasure to program in scala!

Vincent


richard emberson
Joined: 2010-03-22,
User offline. Last seen 42 years 45 weeks ago.
ambiguous reference to overloaded definition

What is the reasoning behind have the compiler be able to
resolve calls to info0 but not info1?

class Foo {
def info0(m: String) { }
def info0(m: String, args: Any*) { }

def info1(m: =>String) { }
def info1(m: =>String, args: Any*) { }
}

object VarArgs {
def main(args: Array[String]) {
val foo = new Foo
foo.info0("hello")
foo.info1("world")
}
}

# scalac VarArgs.scala
VarArgs.scala:16: error: ambiguous reference to overloaded definition,
both method info1 in class Foo of type (m: => String,args: Any*)Unit
and method info1 in class Foo of type (m: => String)Unit
match argument types (java.lang.String)
foo.info1("world")
^
one error found

Richard

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland