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

Ale*_*x O 2 constructor scala list constructor-overloading

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

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中有更好的方法吗?(除了列出[任何]并测试元素)

谢谢!

ste*_*tew 5

在一个伴随对象上创建函数,它以类型安全的方式为您构造,可以在编译时检查:

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

object myClass {
  def fromStrings(strings: List[String]) = {
    val c = new myClass
    c.someStrings = strings
  }
  def fromInts(ints: List[Int]) = {
    val c = new myClass
    c.someStrings = ints.map(_.toString)
  }
}

object Usage {
  val c1 = myClass.fromStrings(List("a","b","c"))
  val c2 = myClass.fromInts(List(1,2,3))
}
Run Code Online (Sandbox Code Playgroud)

当你可以在编译时检查类型时,我会强烈建议你避免一般的重载,或者在运行时检查类型