Hi!
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 {
cleanup(value)
}
}
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