在科特林中将对象数据值组合成单个字符串
Combine object data value into single string in kotlin
嘿,我有 Event
的对象。我想将所有 属性 值组合成单个字符串。我这样做没有任何问题。我想知道有没有更好的方法来优化这段代码在内存、效率等方面
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")
)
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)
嘿,我有 Event
的对象。我想将所有 属性 值组合成单个字符串。我这样做没有任何问题。我想知道有没有更好的方法来优化这段代码在内存、效率等方面
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")
)
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)