为什么Scala需要重复构造函数? (java.lang.NoSuchMethodException) [英] Why Scala needs duplicate constructor? (java.lang.NoSuchMethodException)
问题描述
我在Hadoop作业中收到此错误。
java.lang.NoSuchMethodException:< PackageName>。< ClassName>。< init>(< parameters> ;)
在大多数Scala代码中,您可以在编译时使用它。但是由于这个工作在运行时被调用,所以我没有在编译时捕获它。
我认为默认参数会导致构造函数同时创建两个签名,单一的论点。
class BasicDynamicBlocker(args:Args,evaluation:Boolean = false)使用HiveAccess扩展Job(args){
/ /我需要这样做:
def this(args:Args)= {
this(args,false)
}
...
}
我学会了使用重载构造函数此
。 (我想写出来以防别人帮助别人。)
我也有一些小问题。对我来说,这似乎还是多余的。是否有原因Scala语言的设计限制要求这样做?解析方案
它不是像当你有默认参数时,你会得到重载生成对于每种可能的情况,例如:
$ p $ def $(def:int = 4,str:String =)= ???
您希望编译器生成
<$ p $方法(str:String)=方法(4,str)
def方法()=方法(int,int)=方法(num,)
def方法方法(4,)
但事实并非如此。
您将改为为每个默认参数生成方法(在伴随对象中)
def方法$ default $ 1:Int = 4
def method $ default $ 2:String =a
并且每当你在代码中说出来的时候
method(str =a)
它会变成
方法(方法$ default $ 1,a)
所以在你的情况下,签名 this(args:Args)
就是不存在,只有2个参数版本。
你可以在这里阅读更多: http://docs.scala-lang.org/sips/completed/named-and-default-arguments.html
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?
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
这篇关于为什么Scala需要重复构造函数? (java.lang.NoSuchMethodException)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!