Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

323
Views
How to export Kotlin's data class list to CSV in android?

I am able to find method for exporting Java's list of POJO to csv but unable to find a method to export Kotlin's list of data class to CSV.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You can use the solution offered by this medium article:

To sum up

You can create a simple generic function

import java.io.FileWriter

inline fun <reified T> writeCsvFile(data: Collection<T>, fileName: String) {
    FileWriter(fileName).use { writer ->
        csvMapper.writer(csvMapper.schemaFor(T::class.java).withHeader())
                .writeValues(writer)
                .writeAll(data)
                .close()
    }
}

I tested it with the following dependencies:

com.fasterxml.jackson.dataformat:jackson-dataformat-csv:2.11.1
com.fasterxml.jackson.module:jackson-module-kotlin:2.12.5
over 4 years ago · Santiago Trujillo Report

0

This can be achieved using basic Kotlin instead of an external library.

data class

data class Category(
    val id: String,
    val name: String,
)

utility function

fun <T> csvOf(
    headers: List<String>,
    data: List<T>,
    itemBuilder: (T) -> List<String>
) = buildString {
    append(headers.joinToString(",") { "\"$it\"" })
    append("\n")
    data.forEach { item ->
        append(itemBuilder(item).joinToString(",") { "\"$it\"" })
        append("\n")
    }
}

usage

fun main() {
    val firstCategory = Category(0, "Phone")
    val secondCategory = Category(1, "Laptop")
    val categories = listOf(firstCategory, secondCategory)
    val csv = csvOf(
        listOf("id", "name"),
        categories
    ) {
        listOf(it.id.toString(), it.name)
    }
    println(csv)
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!