Kotlin: appendText and trailing resources

I'm new to Kotlin, but I have a strong Java background (Java is my day job). I love some of the shortcuts in Kotlin. One of them is File.appendText (). It is very convenient, IMO.

My question is about closing resources. If I used the author, I would do something like this:

out8.writer().use { ... }

But I don’t see anything directly in the appendText method, which indicates the closure of resources. Is Kotlin doing this behind the scenes for me, or is this something I should worry about differently?

Thank.

+4
source share
2 answers

You can simply go over to the implementation appendTextin your IDE to find out ( Ctrl + Bon Windows, ⌘Bon Mac).

:

public fun File.appendText(text: String, charset: Charset = Charsets.UTF_8): Unit 
    = appendBytes(text.toByteArray(charset))

appendBytes, :

public fun File.appendBytes(array: ByteArray): Unit 
    = FileOutputStream(this, true).use { it.write(array) }

, use , .

+4

, appendText Writer, .

use java-7 try-with-resource. . File # appendText .

IF File # appendText. :

out8.appendText("content")

IF , File # bufferedWriter() , File # appendText . :

out8.bufferedWriter().use{ 
    it.append("first").append("second") 
}
0

Source: https://habr.com/ru/post/1682253/


All Articles