implicit final classTryThenClose[T <: AnyRef { def close(): Unit }] extends AnyVal
Implementation for a tryThenClose extension method meant for closeable resources,
like input streams, for safe disposal of resources.
This example:
import monifu.syntax.TryThenClose
import java.io.{FileReader, BufferedReader}
val firstLine =
new BufferedReader(new FileReader("file.txt")).tryThenClose { in =>
in.readLine()
}
Is equivalent to this:
import java.io.{FileReader, BufferedReader}
val fistLine = {
val in = new BufferedReader(new FileReader("file.txt"))
try {
in.readLine()
} finally {
in.close()
}
}
Actually for this to work it doesn't have to be a Java
Closable as the type-checking is based
on structural typing (yet because it's implemented as a macro, the actual call is not reflective).
import monifu.syntax.TryThenClose
class Foo { def close() = println("CLOSING") }
new Foo().tryThenClose { _ =>
println("Yay!")
}
Implementation for a
tryThenClose
extension method meant for closeable resources, like input streams, for safe disposal of resources.This example:
Is equivalent to this:
Actually for this to work it doesn't have to be a Java Closable as the type-checking is based on structural typing (yet because it's implemented as a macro, the actual call is not reflective).