Skip to content

Commit e0c5211

Browse files
committed
Fixes Iterable#toString forcing elements
Fixes scala/bug#11785 This changes the implementation of Iterable#toString to not force the evaluation of its elements unless it extends StrictOptimizedIterableOps.
1 parent ebe776e commit e0c5211

File tree

2 files changed

+18
-8
lines changed

2 files changed

+18
-8
lines changed

src/library/scala/collection/Iterable.scala

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -68,12 +68,12 @@ trait Iterable[+A] extends IterableOnce[A]
6868
protected[this] def stringPrefix: String = "Iterable"
6969

7070
/** Converts this $coll to a string.
71-
*
72-
* @return a string representation of this collection. By default this
73-
* string consists of the `className` of this $coll, followed
74-
* by all elements separated by commas and enclosed in parentheses.
7571
*/
76-
override def toString = mkString(className + "(", ", ", ")")
72+
override def toString: String =
73+
this match {
74+
case _: StrictOptimizedIterableOps[_, _, _] => mkString(className + "(", ", ", ")")
75+
case _ => className + "(<iterable>)"
76+
}
7777

7878
/** Analogous to `zip` except that the elements in each collection are not consumed until a strict operation is
7979
* invoked on the returned `LazyZip2` decorator.

test/junit/scala/collection/IterableTest.scala

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,7 @@ class IterableTest {
243243
override def className = "Fu"
244244
}
245245
val foo = new Foo
246-
Assert.assertEquals("Fu()", foo.toString)
246+
Assert.assertEquals("Fu(<iterable>)", foo.toString)
247247
}
248248

249249
@Test
@@ -254,7 +254,7 @@ class IterableTest {
254254

255255
}
256256
val foo = new Foo
257-
Assert.assertEquals("Bar()", foo.toString)
257+
Assert.assertEquals("Bar(<iterable>)", foo.toString)
258258
}
259259

260260
@Test
@@ -266,7 +266,17 @@ class IterableTest {
266266

267267
}
268268
val foo = new Foo
269-
Assert.assertEquals("Fu()", foo.toString)
269+
Assert.assertEquals("Fu(<iterable>)", foo.toString)
270+
}
271+
272+
@Test
273+
def infiniteIterable: Unit = {
274+
class Foo extends Iterable[Int] {
275+
def iterator = Iterator.continually(42)
276+
override def className = "Fu"
277+
}
278+
val foo = new Foo
279+
Assert.assertEquals("Fu(<iterable>)", foo.toString)
270280
}
271281

272282
@Test

0 commit comments

Comments
 (0)