Skip to content

Instantly share code, notes, and snippets.

@YusukeIwaki
Created January 6, 2018 06:05
Show Gist options
  • Save YusukeIwaki/dc3acad41c18a927c8b2d1de40319707 to your computer and use it in GitHub Desktop.
Save YusukeIwaki/dc3acad41c18a927c8b2d1de40319707 to your computer and use it in GitHub Desktop.
backing fieldのgetでCloseしないといけないリソースを返して、そいつをuseしたときにitで新たなリソースが生成されないことを確認する
import java.io.Closeable
class Resource: Closeable {
init {
println("resource ref +1")
}
fun play() {
println("play")
}
override fun close() {
println("resource ref -1")
}
}
class Practice {
private val resource
get() = Resource()
fun execute() {
resource.use {
it.play()
}
resource.use {
resource.use {
it.play()
it.play()
}
resource.use {
it.play()
it.play()
it.play()
}
}
}
}
fun main(args: Array<String>) {
Practice().execute()
}
@YusukeIwaki
Copy link
Author

実行結果

resource ref +1
play
resource ref -1
resource ref +1
resource ref +1
play
play
resource ref -1
resource ref +1
play
play
play
resource ref -1
resource ref -1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment