Home > Enterprise >  Combine object data value into single string in kotlin
Combine object data value into single string in kotlin

Time:06-03

Hey I have object of Event. I want to combine all property value into single string. I did this without any problem. I want to know is there any better way to optimise this code in memory, efficiency etc.

SingleEventString.kt

fun main() {
    var newString: String? = null
    val eventList = createData()
    eventList.forEachIndexed { index, event ->
        val title = event.title
        val status = event.status
        if (!title.isNullOrEmpty()) {
            newString = if(index == 0){
                "$title"
            }else{
                "$newString $title"
            }
        }
        if (!status.isNullOrEmpty()) {
            newString = "$newString $status"
        }
    }
    println(newString)
}

data class Event(val title: String? = null, val status: String? = null)

fun createData() = listOf(
    Event("text 1", "abc"),
    Event("text 2", "abc"),
    Event("text 3", "abc"),
    Event("text 4", "abc"),
    Event("", "abc"),
    Event(null, "abc")
)

CodePudding user response:

data class Event(val title: String? = null, val status: String? = null)

fun createData() = listOf(
  Event("text 1", "abc"),
  Event("text 2", "abc"),
  Event("text 3", "abc"),
  Event("text 4", "abc"),
  Event("", "abc"),
  Event(null, "abc")
)

val newString = createData()
  .joinToString(" ") { "${it.title?: ""} ${it.status?: ""}".trim() }

println(newString)
  • Related