Scoped use statement

C# introduced a really neat usage of the using keyword. It follows closely with the declaration style of a variable, but is disposed when you exit the current scope.

It’s nice that kotlin has .use available, although I’m wondering if kotlin has anything to keep code clean in a similar way that C# is now offering.

(If not, I wonder if any kotlin maintainers reading might be inclined to consider adding scoped-use somewhere on the roadmap :wink: )

Kotlin doesn’t have anything like C#s

using var reader = new StringReader(manyLines);

Maybe you could do something like this

class UsingScope(var usingList: MutableList<Closeable> = mutableListOf()){
   fun <T: Closeable>using(closeable: T): T = closeable.also { usingList.add(it) }
inline fun <R>usingScope(block: UsingScope.() -> R): R {
    val scope = UsingScope()
    val result = scope .block()
    scope.usingList.forEach { it.close() }
    return result

   val reader = using(StringReader(...))

I just wrote that without access to an IDE but it should work in general. Might need some cleanup and proper hiding of internal properties, etc.

This really shows the power of kotlin lambdas and inline functions. There are so many language features that kotlin can just implement in a library without having any real downside to useability.

1 Like