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

This commit is contained in:
James Strachan
2012-03-05 13:22:16 +00:00
parent 12875e1ca2
commit bb593d78a9
2 changed files with 5 additions and 5 deletions
+4 -4
View File
@@ -67,8 +67,8 @@ private val stdin : BufferedReader = BufferedReader(InputStreamReader(object : I
inline fun readLine() : String? = stdin.readLine() inline fun readLine() : String? = stdin.readLine()
/** Uses the given resource then closes it to ensure its closed again */ /** Uses the given resource then closes it down correctly whether an exception is thrown or not */
inline fun <T: Closeable, R> T.foreach(block: (T)-> R) : R { inline fun <T: Closeable, R> T.use(block: (T)-> R) : R {
var closed = false var closed = false
try { try {
return block(this) 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.buffered(bufferSize: Int) = BufferedReader(this, bufferSize)
inline fun Reader.foreachLine(block: (String) -> Unit): Unit { inline fun Reader.foreachLine(block: (String) -> Unit): Unit {
this.foreach{ this.use{
val iter = buffered().lineIterator() val iter = buffered().lineIterator()
while (iter.hasNext) { while (iter.hasNext) {
val elem = iter.next() val elem = iter.next()
@@ -135,7 +135,7 @@ inline fun Reader.foreachLine(block: (String) -> Unit): Unit {
} }
} }
inline fun <T> Reader.useLines(block: (Iterator<String>) -> T): T = this.buffered().foreach<BufferedReader, T>{block(it.lineIterator())} inline fun <T> Reader.useLines(block: (Iterator<String>) -> T): T = this.buffered().use<BufferedReader, T>{block(it.lineIterator())}
/** /**
* Returns an iterator over each line. * Returns an iterator over each line.
* <b>Note</b> the caller must close the underlying <code>BufferedReader</code> * <b>Note</b> the caller must close the underlying <code>BufferedReader</code>
+1 -1
View File
@@ -37,7 +37,7 @@ class IoTest() : TestCase() {
val list = ArrayList<String>() val list = ArrayList<String>()
val reader = sample().buffered() val reader = sample().buffered()
reader.foreach{ reader.use{
while (true) { while (true) {
val line = it.readLine() val line = it.readLine()
if (line != null) if (line != null)