小编Ale*_*x O的帖子

是否可以重载接受scala中列表的构造函数?

我试图将构造函数重载到一个类,以便它可以接受两种不同类型的对象的列表:

class myClass(){
  var someStrings: List[String]=List[String]()
  println("hello!")

  def this(strings : List[String])={
    this()
    this.someStrings=strings
  }

  def this(ints: List[Int])={
    this()
    this.someStrings=ints.map(x => x.toString)
  }
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,接受一个int或字符串列表,并将字符串列表保存到变量some​​Strings.上面的代码不起作用:

error: double definition:
constructor myClass: (strings: List[String])myClass at line 12 and
constructor myClass: (ints: List[Int])myClass at line 17
have same type after erasure: (strings: List)myClass
             def this(ints: List[Int])={
             ^
Run Code Online (Sandbox Code Playgroud)

在scala中有更好的方法吗?(除了列出[任何]并测试元素)

谢谢!

constructor scala list constructor-overloading

2
推荐指数
1
解决办法
198
查看次数