Is there some syntax similar to SafeRelease in COM


#1
var stream : InputStream? = ...
...
//SafeRelease
if(stream != null) {
    stream .close()
    stream = null
}

Can this four-line code be converted to more elegant and simpler form?


#2

Maybe like this

openInput()?.let {
...
it.close()
}

I don’t know whats safe about it anyways :slight_smile:


#3

http://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/use.html


#4

The key point is in fact null assignment. I don’t know if the inline lambda will help


#5

In lambda case I showed there is no external named variable to capture null value. It will be executed only in case of stream being non null. If you don’t escape ‘it’ in lambda body there is no reason to null anything.
Your code suggests you have class which wraps stream with ‘close’ method safe to be called multiple times(idempotent). Variant with lambda replaces such wrapping class in many use cases.