I implement a Scala class with an overloaded method that can take an Iterable[String]
or a String*
varargs parameter:
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")
}
}
I expect x2
to be a new object with names c
and d
, but the value x2
cannot be created because of an infinite recursion causing a StackOverflowError:
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)
...
What's wrong with the code?