3

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")
)

1 Answer 1

6
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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.