Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine object data value into single string in kotlin

Tags:

kotlin

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")
)
like image 280
Vivek Modi Avatar asked Nov 18 '25 13:11

Vivek Modi


1 Answers

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)
like image 184
lukas.j Avatar answered Nov 21 '25 07:11

lukas.j



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!