Created
January 22, 2017 15:52
-
-
Save Takhion/aa68f68af5728a19b1e4ecc8620611d3 to your computer and use it in GitHub Desktop.
Flat `use` in Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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