Skip to content

Instantly share code, notes, and snippets.

@Takhion
Created January 22, 2017 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Takhion/aa68f68af5728a19b1e4ecc8620611d3 to your computer and use it in GitHub Desktop.
Save Takhion/aa68f68af5728a19b1e4ecc8620611d3 to your computer and use it in GitHub Desktop.
Flat `use` in Kotlin
fun test() {
val lines = use {
val a = File("path1").reader().use
val b = File("path2").reader().use
val c = File("path3").reader().use
a.readLines() + b.readLines() + c.readLines()
}
}
inline fun <T> use(block: UseBlock.() -> T): T = UseBlock().run { block().also { closeAll() } }
class UseBlock @PublishedApi internal constructor() {
private val closeables = mutableListOf<Closeable>()
@PublishedApi internal fun closeAll() {
closeables.forEach(Closeable::close)
}
val <T : Closeable> T.use: T get() = also { closeables.add(it) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment