Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Scala needs duplicate constructor? (java.lang.NoSuchMethodException)

Tags:

scala

hadoop

I was receiving this error in my Hadoop job.
java.lang.NoSuchMethodException: <PackageName>.<ClassName>.<init>(<parameters>) In most Scala code, you would have it in compile time. But since this job is called in runtime I was not catching it in compile time.

I would think default parameter would cause constructors with both signatures to be created, one taking a single argument.

class BasicDynamicBlocker(args: Args, evaluation: Boolean = false) extends    Job(args) with HiveAccess {
//I NEEDED THIS TOO:
 def this(args: Args) = {
   this(args, false)
 }

... }

I learned the hard way that I needed to declare the overloaded constructor using this. (I wanted to write this out in case it helps someone else.) I also have a small questions. It still seems redundant to me. Is there a reason Scala language's design restrictions require this?

like image 309
Ozgur Ozturk Avatar asked Apr 02 '26 10:04

Ozgur Ozturk


1 Answers

It is not like when you have default parameter you will get overloads generated for each possible case, like for example:

def method(num: Int = 4, str: String = "") = ???

you expect compiler to generate

def method(num: Int) = method(num, "")
def method(str: String) = method(4, str)
def method() = method(4, "")

but that is not the case.

You will instead have generated methods (in companion object), for each default param

def method$default$1: Int = 4
def method$default$2: String = "a"

and whenever you say in your code

method(str = "a")

it will be just changed to

method(method$default$1, "a")

So in your case, constructor with signature this(args: Args) just did not exist, there was only the 2 param version.

You can read more here: http://docs.scala-lang.org/sips/completed/named-and-default-arguments.html

like image 162
Łukasz Avatar answered Apr 04 '26 08:04

Łukasz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!