Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

extension methods - Try-with-resources in Kotlin

When I tried to write an equivalent of a Java try-with-resources code in Kotlin, it didn't work for me.

I tried different variations of the following:

try (writer = OutputStreamWriter(r.getOutputStream())) {
    // ...
}

But neither works.

Does anyone know what should be used instead? Apparently Kotlin grammar doesn't have definition for such a construct, but maybe I'm missing something. It defines grammar for try block as follows:

try : "try" block catchBlock* finallyBlock?;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is use-function in kotlin stdlib (src).

How to use it:

OutputStreamWriter(r.getOutputStream()).use {
    // by `it` value you can get your OutputStreamWriter
    it.write('a')
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...