Skip to content

Commit 0694036

Browse files
authored
Merge pull request scala#6679 from xuwei-k/Stream-take
override Stream#take
2 parents dd23668 + 85c0ee7 commit 0694036

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

src/library/scala/collection/immutable/LazyList.scala

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -739,6 +739,12 @@ sealed abstract class Stream[+A] extends AbstractSeq[A] with LinearSeq[A] with L
739739
}
740740
}
741741

742+
override def take(n: Int): Stream[A] = {
743+
if (n <= 0 || isEmpty) Stream.empty
744+
else if (n == 1) new Stream.Cons(head, Stream.empty)
745+
else new Stream.Cons(head, tail.take(n - 1))
746+
}
747+
742748
/** LazyList specialization of foldLeft which allows GC to collect along the
743749
* way.
744750
*

test/junit/scala/collection/immutable/StreamTest.scala

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,4 +237,15 @@ class StreamTest {
237237
s2.flatMap { i => (if(i < 5) None else Some(i)): Option[Int] }.headOption
238238
assertEquals(5, it1.current)
239239
}
240+
241+
@Test
242+
def t10883: Unit = {
243+
var value: Int = -1
244+
Stream.iterate(0){ a =>
245+
val next = a + 1
246+
value = next
247+
next
248+
}.take(3).toList
249+
assertEquals(value, 2)
250+
}
240251
}

0 commit comments

Comments
 (0)