Hey, could anyone help me with something? with th...
# getting-started
l
Hey, could anyone help me with something? with the data class below:
Copy code
data class Item(val completed: Boolean, val details: String? = null)
and a list:
Copy code
val p = listOf(
        Item(true, "one"),
        Item(false, "two"),
        Item(true, "three")
	)
I need to transform this data (truncate the second value in the Item to return something like:
Copy code
listOf(
        Item(true, "o"),
        Item(false, "t"),
        Item(true, "t")
	)
Im trying:
Copy code
val p = listOf(
        Item(true, "one"),
        Item(false, "two"),
        Item(true, "three")
	)
    
    println(p.map { (_,details) -> details?.take(1) })
but it returns: [o, t, t] What’s the best way to do this in Kotlin? Thank you in advance
a
how about
Copy code
item -> item.copy(details = item.details?.take(1))
💯 2
🤩 2
l
huh
thanks so much
🙏 1
m
the fact that you said huh means there is a need for an explanation
The dataclasses you showed are immutable (you provided
val
). This means that whatever input you show, for them you need to recreate the entire dataclass if you want it's data to be modified.
Copy code
item -> item.copy(details = item.details?.take(1))
is the same as:
Copy code
item -> Item(item.completed, item.details?.take(1))
as in, you are creating a new item, with modified data