Overloaded methods in Scala
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")
}
Advertisement