Scala中具有多参数或序列的构造函数?(Constructors with multi

编程入门 行业动态 更新时间:2024-10-28 19:20:58
Scala中具有多参数或序列的构造函数?(Constructors with multi-parameter or sequences in Scala?)

这里是一个基本的例子..我不能让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) }

更多推荐

本文发布于:2023-08-01 20:37:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1363607.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有多   序列   函数   参数   Scala

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!