C# using() in Kotlin



I experimented with implementing something along the lines of C# using construct in Kotlin. Maybe a built-in support still is to be preferred, but it looks quite nice anyway.


import java.io.File
import java.io.FileReader

fun unwindProtect<T, R>(create: () -> T, transform: (T) -> R, cleanup: (T) -> Unit): R {
  val value = create()
  try {
  return transform(value)
  } finally {

fun withOpenFile<T>(filename: String, body: (FileReader) -> T): T {
  return unwindProtect({ File(filename).reader() }, body, { f -> f.close() })

fun main(args: Array<String>) {
  withOpenFile(“hello.txt”, { reader -> println(reader.readText()) })

unwindProtect() is a helper function. The name comes from Common Lisps unwind-protect.
The only thing that really could be improved here is that I had to use “reader ->” to introduce a name for the passed value. I suppose one could use “it” instead and skip that.

So what do you people think about this? Is special syntax for this common pattern needed?
I think I would like to have a special syntax, but I’m used to C#.

Regards, Flow


We are on the fence here. See this discussion: http://youtrack.jetbrains.com/issue/KT-2984


As an aside the standard library has a 'use' extension function on any java.lang.Closeable type such as the java.io streams and reader/writers so you can do things like...

FileReader("foo.txt").use { reader ->   ... }

which ensures propery try/catch and closing behaviour. The issue Andrey brings up is around being able to use multiple resources in a more DRY syntax (rather like java's try-with-resources syntax or Scala's for statement).