diff --git a/stdlib/ktSrc/JavaIo.kt b/stdlib/ktSrc/JavaIo.kt index 0eba940c2a1..e687c90a655 100644 --- a/stdlib/ktSrc/JavaIo.kt +++ b/stdlib/ktSrc/JavaIo.kt @@ -67,8 +67,8 @@ private val stdin : BufferedReader = BufferedReader(InputStreamReader(object : I inline fun readLine() : String? = stdin.readLine() -/** Uses the given resource then closes it to ensure its closed again */ -inline fun T.foreach(block: (T)-> R) : R { +/** Uses the given resource then closes it down correctly whether an exception is thrown or not */ +inline fun T.use(block: (T)-> R) : R { var closed = false try { return block(this) @@ -126,7 +126,7 @@ inline fun Reader.buffered(): BufferedReader = if(this is BufferedReader) this e inline fun Reader.buffered(bufferSize: Int) = BufferedReader(this, bufferSize) inline fun Reader.foreachLine(block: (String) -> Unit): Unit { - this.foreach{ + this.use{ val iter = buffered().lineIterator() while (iter.hasNext) { val elem = iter.next() @@ -135,7 +135,7 @@ inline fun Reader.foreachLine(block: (String) -> Unit): Unit { } } -inline fun Reader.useLines(block: (Iterator) -> T): T = this.buffered().foreach{block(it.lineIterator())} +inline fun Reader.useLines(block: (Iterator) -> T): T = this.buffered().use{block(it.lineIterator())} /** * Returns an iterator over each line. * Note the caller must close the underlying BufferedReader diff --git a/testlib/test/IoTest.kt b/testlib/test/IoTest.kt index 058f610c32f..27a95b35780 100644 --- a/testlib/test/IoTest.kt +++ b/testlib/test/IoTest.kt @@ -37,7 +37,7 @@ class IoTest() : TestCase() { val list = ArrayList() val reader = sample().buffered() - reader.foreach{ + reader.use{ while (true) { val line = it.readLine() if (line != null)