AutoClosable.use defined in
kotlin-stdlib. The first variant in my opinion is more simple and efficient, while the second generate more bytecode and creates more variable slots. But when applied to object what implements both interfaces (
Socket for example), second variant is used. As I understand, compiler applies rule “use more specific subtype”. Can we somehow disable second variant and use only first?
I think you can cast the variable as
AutoCloseable so that
Closable.use will be outruled. But that isn’t much convenient as you’ll have to save the value inside a separate variable to be able to use it inside
use lambda having the original type.
Another option is to import
kotlin.io package with alias. When importing something with alias it becomes unavailable by its original name:
import kotlin.io.use as doNotUse
Meanwhile we’re planning improvements in the compiler to overcome the limitations that hold us from optimizing
Closeable.use, see https://youtrack.jetbrains.com/issue/KT-16028
The main difference between them is that
Closeable.use() doesn’t use a new
addSuppressed() method. For Java 7+ compiler should always apply this mechanism to all
(Auto)Closeable types, but unfortunately Kotlin favours the older function in many cases.
Well, it seems what “cleaner” solution is to write our own
use() function analog and use it instead. But then either we should not forget about right
import, or call this function some differently (
auto(), for example).
By the way, link to KT-16028 cannot be opened. “You have no permissions to view this page”