From bb593d78a9e142c4176020c68f25e73ed5fd5f22 Mon Sep 17 00:00:00 2001 From: James Strachan Date: Mon, 5 Mar 2012 13:22:16 +0000 Subject: [PATCH] refactored Closable.foreach to be Closeeble.use{ ... } for now as an interim solution until some try-with-resources syntax is available as in KT-1475 --- stdlib/ktSrc/JavaIo.kt | 8 ++++---- testlib/test/IoTest.kt | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) 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)