Skip to content

Instantly share code, notes, and snippets.

@crowjdh
Created May 3, 2016 15:27
Show Gist options
  • Select an option

  • Save crowjdh/1b026b0447ebd00b1b97968950526e6f to your computer and use it in GitHub Desktop.

Select an option

Save crowjdh/1b026b0447ebd00b1b97968950526e6f to your computer and use it in GitHub Desktop.
Extension function expression for Closeable.use in Kotlin
/**
* Built-in "use" function:
* resources.openRawResource(resId).use { inputStream ->
* inputStream.doSomething1()
* inputStream.doSomething2()
* }
*
* New "use" function:
* resources.openRawResource(resId).use {
* this.doSomething1()
* doSomething2()
* }
*
* See this video for more information: https://youtu.be/A2LukgT2mKc?t=23m43s
*/
inline fun <T: Closeable, R> T.use(block: T.() -> R): R {
use { closable ->
return closable.block()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment