【发布时间】:2015-01-12 05:58:08
【问题描述】:
我实现了一个带有重载方法的 Scala 类,该方法可以采用 Iterable[String] 或 String* 可变参数:
class StackOverflow(names: Iterable[String]) {
// This function creates a copy of the StackOverflow object
// copy is needed but this cannot be a case class.
private def copy(names: Iterable[String] = names) = new StackOverflow(names) // <- line 19
// overloaded methods
def withNames(names: Iterable[String]) = this.copy(names = names) // <- line 24
def withNames(names: String*) = require(names.nonEmpty); withNames(names.toIterable) // <- line 26
}
object App {
def main(args: Array[String]) = {
val x1 = new StackOverflow(Seq("a", "b"))
val x2 = x1.withNames("c", "d")
}
}
我希望 x2 是一个名为 c 和 d 的新对象,但由于无限递归导致 StackOverflowError,无法创建值 x2:
Exception in thread "main" java.lang.StackOverflowError
at scala.collection.LinearSeqLike$class.thisCollection(LinearSeqLike.scala:48)
at scala.collection.immutable.List.thisCollection(List.scala:84)
at scala.collection.immutable.List.thisCollection(List.scala:84)
at scala.collection.IterableLike$class.toIterable(IterableLike.scala:87)
at scala.collection.AbstractIterable.toIterable(Iterable.scala:54)
at test.StackOverflow.<init>(StackOverflow.scala:26)
at test.StackOverflow.copy(StackOverflow.scala:19)
at test.StackOverflow.withNames(StackOverflow.scala:24)
at test.StackOverflow.<init>(StackOverflow.scala:26)
at test.StackOverflow.copy(StackOverflow.scala:19)
at test.StackOverflow.withNames(StackOverflow.scala:24)
...
代码有什么问题?
【问题讨论】: