Liz Douglass

Overloaded methods in Scala

leave a comment »

I recently discovered that it’s not possible to have default parameters on more than one overloaded method alternative in Scala. The methods that I was working on looked a bit like this:

class Bar() {
  def foo(data: Map[String, String], list: String, field: String = "username"): Boolean = { 
      //do some processing
      true
  }

  def foo(data: String, list: String, field: String = "username"): Boolean = {
      //do some processing
      true
  }
}

Given that it’s possible to work out which alternative needs to be called from the type of the first argument, I incorrectly assumed that these declarations would be ok . As a work-around I created another pair of overloaded methods (see below). If you know of a better alternative then please let me know.

class Bar() {
  def foo(data: Map[String, String], list: String, field: String): Boolean = {
      //do some processing
      foo(data, list, field)
  }

  def foo(data: String, list: String, field: String): Boolean = {
      //do some processing
      true
  }

  def foo(data: Map[String, String], list: String): Boolean =
      foo(data, list, "username")

  def foo(data: String, list: String): Boolean =
      foo(data, list, "username")
}
Advertisements

Written by lizdouglass

December 15, 2010 at 9:23 am

Posted in Uncategorized

Tagged with

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: