From 323df9498a5818ff04a7ab98190805dcfebfd5b6 Mon Sep 17 00:00:00 2001 From: Denis Mekhanikov Date: Fri, 17 Oct 2014 14:42:24 +0400 Subject: [PATCH] stdlib: fix DropStream & TakeStream mutliple iteration --- .../stdlib/src/kotlin/collections/Stream.kt | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/libraries/stdlib/src/kotlin/collections/Stream.kt b/libraries/stdlib/src/kotlin/collections/Stream.kt index fbeecbe32a0..1da1e790ef7 100644 --- a/libraries/stdlib/src/kotlin/collections/Stream.kt +++ b/libraries/stdlib/src/kotlin/collections/Stream.kt @@ -156,7 +156,7 @@ public class Multistream(private val stream: Stream>) : Stream { } public class TakeStream(private val stream: Stream, - private var count: Int + private val count: Int ) : Stream { { if (count < 0) @@ -164,17 +164,18 @@ public class TakeStream(private val stream: Stream, } override fun iterator(): Iterator = object : Iterator { + var left = count val iterator = stream.iterator(); override fun next(): T { - if (count == 0) + if (left == 0) throw NoSuchElementException() - count-- + left-- return iterator.next() } override fun hasNext(): Boolean { - return count > 0 && iterator.hasNext() + return left > 0 && iterator.hasNext() } } } @@ -221,7 +222,7 @@ public class TakeWhileStream(private val stream: Stream, } public class DropStream(private val stream: Stream, - private var count: Int + private val count: Int ) : Stream { { if (count < 0) @@ -230,12 +231,13 @@ public class DropStream(private val stream: Stream, override fun iterator(): Iterator = object : Iterator { val iterator = stream.iterator(); + var left = count // Shouldn't be called from constructor to avoid premature iteration private fun drop() { - while (count > 0 && iterator.hasNext()) { + while (left > 0 && iterator.hasNext()) { iterator.next() - count-- + left-- } }