javakotlinfilebufferedwritercloseable

Writing and returning a File in Kotlin using a buffer


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.


Solution

  • How about:

    fun List<Contact>.buildCsv(): File {
        val file = File("people.csv")
    
        file.bufferedWriter(Charsets.ISO_8859_1).use { out ->
            out.write("a,b,c,d\n")
            this.forEach {
                out.write(it.toString())
            }
        }
    
        return file
    }