Skip to content

Instantly share code, notes, and snippets.

@yamin8000
Last active August 15, 2022 06:51
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yamin8000/fdbe5ecae4c394c520e69f9e56608df9 to your computer and use it in GitHub Desktop.
Save yamin8000/fdbe5ecae4c394c520e69f9e56608df9 to your computer and use it in GitHub Desktop.
Create CSV from a Kotlin List
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)
}
data class Category(
val id: String,
val name: String,
)
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")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment