这里是一个基本的例子..我不能让scala认识到我希望能够以两种不同的方式初始化我的类:通过现有序列或使用多个参数。
我收到的错误是:
双重定义:方法apply:(params:Int *)chorle.scala.tests.MultiParam和method apply:(pList: Seq [Int])第9行的chorle.scala.tests.MultiParam在擦除后具有相同的类型:(params:Seq)chorle.scala.tests.MultiParam
哪个好,我得到这里发生了什么 - 后编译这两个函数导致相同的头部签名。 但是,实际上它们的工作方式并不一样 - 我无法启用:apply(1,2,3)如果我只有apply(Seq)版本...并且我无法启用apply(seq)the其他方式。 我知道我可以用各种方法修补实际的函数调用,但是我怎样才能在课堂上恰当地解决这个问题并且只有一次? 谢谢!
class MultiParam protected (pList:Seq[Int]) object MultiParam { def apply(pList:Seq[Int]): MultiParam = new MultiParam(pList) def apply(params: Int *): MultiParam = new MultiParam(params) }here's the basic example.. I can't get scala to recognize that I want the ability to initialize my class in 2 different ways: via an existing sequence, or using multiple parameters.
The error I receive is:
double definition: method apply:(params: Int*)chorle.scala.tests.MultiParam and method apply:(pList: Seq[Int])chorle.scala.tests.MultiParam at line 9 have same type after erasure: (params: Seq)chorle.scala.tests.MultiParam
Which ok, I get what's going on here - post compilation both functions result in the same header signature. However, in practice they do not work the same way - I can't envoke : apply(1,2,3) if I only have the apply(Seq) version... and I can't envoke apply(seq) the other way around. I am aware of various ways I could patch the actual function call, but how do I address this properly and only once in the class? Thank you!
class MultiParam protected (pList:Seq[Int]) object MultiParam { def apply(pList:Seq[Int]): MultiParam = new MultiParam(pList) def apply(params: Int *): MultiParam = new MultiParam(params) }最满意答案
那么,它们不能按原样使用,因为无法生成这两种方法。 唯一的解决办法是消除它们的歧义:
object MultiParam { def apply(pList:Seq[Int]): MultiParam = new MultiParam(pList) def apply(param: Int, params: Int *): MultiParam = new MultiParam(param +: params) def apply(): MultiParam = new MultiParam(Nil) }Well, they can't be used as is because there's no way to generate both methods. The only way around it is to disambiguate them:
object MultiParam { def apply(pList:Seq[Int]): MultiParam = new MultiParam(pList) def apply(param: Int, params: Int *): MultiParam = new MultiParam(param +: params) def apply(): MultiParam = new MultiParam(Nil) }更多推荐
发布评论