Scalera tips: default parameters and overloading

It’s time today for a short post which hopefully will help some of you in discovering a new world. Today we are talking about the problems that may arise due to overloading when we have default parameters.

Let’s start defining the basic concepts:

– Overloading: …really?
– Default parameters: in Scala, it is possible to define default parameters in methods. These parameters can be obviated in the method call. With an example:

def getUri(host: String = "localhost", port: Int = 8080): String =
"$host:$port"

getUri("127.0.0.1", 8081) //"127.0.0.1:8081"
getUri(port = 8081) //"localhost:8081"
getUri("127.0.0.1") //"127.0.0.1:8080"
getUri() //"localhost:8080"

Great… and what’s the problem with it?

Let’s create the following trait:

trait A {
  def a(a: Int, p: Boolean = false)
  def a(b: Boolean = false)
}

We now compile and…

giphy2

error: in trait A, multiple overloaded alternatives of method a define default arguments.

However, if we take away the default parameter in the first function:

trait A {
  def a(a: Int, p: Boolean)
  def a(b: Boolean = false)
}

and we compile …..

giphy1

everything works.

What’s the reason for all this mess?

The problem is that the compiler uses default parameters to generate the names of some auxiliary functions that will help in dealing with the methods with default values (we shouldn’t forget that we are still in the JVM). Let’s see the example that is shown in the documentation:

def f(a: Int = 1, b: String)
// generates a method: def f$default$1 = 1
f(b = "3")
// transformed to: f(b = "3", a = f$default$1)

As can be observed, a new function is generated and the call to the original method is overloaded by making use of this function.

After this, we can say that in our messy example, the two auxiliary functions that are created will have this name:

def a$default$1 = false

and this is why a name conflict will arise.

In the second case, given that there is no default parameter in the first method, only one new function will be generated and thus, no conflict will appear.

And this is how our post ends 🙂

Anuncios

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s