Last active
August 15, 2022 06:51
-
-
Save yamin8000/fdbe5ecae4c394c520e69f9e56608df9 to your computer and use it in GitHub Desktop.
Create CSV from a Kotlin List
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data class Category( | |
val id: String, | |
val name: String, | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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