我试图将构造函数重载到一个类,以便它可以接受两种不同类型的对象的列表:
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或字符串列表,并将字符串列表保存到变量someStrings.上面的代码不起作用:
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中有更好的方法吗?(除了列出[任何]并测试元素)
谢谢!