I can't seem to find this question yet, but what is the simplest, most-idiomatic way of opening/creating a file, writing to it, and then closing it? Looking at the kotlin.io reference and the Java documentation I managed to get this:
fun write() {
val writer = PrintWriter("file.txt") // java.io.PrintWriter
for ((member, originalInput) in history) { // history: Map<Member, String>
writer.append("$member, $originalInput\n")
}
writer.close()
}
This works, but I was wondering if there was a "proper" Kotlin way of doing this?
It mostly looks ok to me. The only thing different I would do is use the "use" extension defined in ReadWrite to auto close the writer.
A bit more idiomatic. For PrintWriter, this example:
The
for
loop, orforEach
depends on your style. No reason to useappend(x)
since that is basicallywrite(x.toString())
and you already give it a string. Andprintln(x)
basically doeswrite(x)
after converting anull
to"null"
. Andprintln()
does the correct line ending.If you are using
data
classes of Kotlin, they can already be output because they have a nicetoString()
method already.Also, in this case if you wanted to use
BufferedWriter
it would produce the same results:Also you can use
out.newLine()
instead of\n
if you want it to be correct for the current operating system in which it is running. And if you were doing that all the time, you would likely create an extension function:And then use that instead:
And that's how Kotlin rolls. Change things in API's to make them how you want them to be.
Wildly different flavours for this are in another answer: https://stackoverflow.com/a/35462184/3679676
At the very minimum, you could use:
FileWriter(filename).use { it.write(text) }
FileWriter is a convenience class for writing character files (provided by Java, and hence available in Kotlin). It extends Closeable, and hence can be used by Kotlin's ".use" extension method.
The .use extension method automatically closes the calling object once the block exits, thus providing an idiomatic way to close the file after it's written.
Other fun variations so you can see the power of Kotlin:
A quick version by creating the string to write all at once:
Or assuming you might do other functional things like filter lines or take only the first 100, etc. You could go this route:
Or given an
Iterable
, allow writing it to a file using a transform to a string, by creating extension functions (similar towriteText()
version above, but streams the content instead of materializing a big string first):used as any of these:
or use default toString() on each item:
Or given a
File
, allow filling it from anIterable
, by creating this extension function:with usage of:
or use default toString() on each item:
which if you had the other
toFile
extension already, you could rewrite having one extension call the other:Some Kotlin magic allows to omit referencing the stream on each read or write call: