I'm working on a function to process some data and output the results as a csv file. I am using a 'use' block to wrap the function and ensure all the resources are closed. the problem I am running into is that I want the function to return the newly created File to the caller. The use block has the ability to return a value, however since it is being called with a bufferedWriter, there is no ability to actually return the File object from inside the block. Can anyone offer suggestions on how to solve this?
I want to do something like:
fun List<Contact>.buildCsv():File
{
return File("people.csv").bufferedWriter(Charsets.ISO_8859_1).use { out ->
out.write("a,b,c,d\n")
this.forEach {
out.write(it.toString())
}
}
}
but that code does not compile.
Filein Java. It's not what you think. The functionality of that class is really to manipulate paths and the like. It really has little to do with the actual content of a file system. If you really want to return a 'file' you would do well to think of it as returning a stream to the actual content (and all that entails)Files and hence the file system. It gets messy when unit testing. (You do write unit tests, right?) Instead of aFile, pass anOutputStreamor aStreamWriter. In a test you can pass one that collects what gets written in a byte array or string. In real life, you can still pass a stream that writes to a file. But this decouples I/O from the logic in yourbuildCsvfunction.