O'Reilly logo

Scala Puzzlers by Nermin Šerifovic, Andrew Phillips

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Puzzler 18

Information Overload

Overloaded methods are a common way of providing functions that can be applied to various combinations of arguments. Some care is required here, since new versions of an overloaded method can mean that the compiler needs to distinguish between multiple applicable versions where the method is called. If the compiler cannot identify a single, most applicable method, compilation will fail:

  def foo(n: Int, a: Any) { 
    println(s"n: ${n}, a: ${a}") }
    scala> foo(12)
  n: 1, a: 2
    object A {
    def foo(n: Int, a: Any) { 
      println(s"n: ${n}, a: ${a}") }
    def foo(a: Any, n: Int) { 
      println(s"a: ${a}, n: ${n}") }
  }
    scala> A.foo(12)
  <console>:10: error: ambiguous reference to 
    overloaded definition,
  both method foo in object A of type (a: Any, n: Int)Unit ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required