In your first example:
var userList = mutableListOf<User>()
var nameList= userList.map { it.name }
The question "What's the type of nameList
?" has a simple answer: List<String>
. So let me ask you a similar question: What's the type of withoutAgeList
? The answer to that question informs the answer to your question.
Perhaps a user without the age property is a separate AgelessUser
class, meaning withoutAgeList
is of type List<AgelessUser>
. In that case, I suggest either a constructor or a factory function that builds AgelessUser
from User
, and you want one of these:
val withoutAgeList = userList.map { AgelessUser(it) } // constructor
val withoutAgeList = userList.map { agelessUserOf(it) } // factory
Alternatively, maybe the age
property in User
is nullable and immutable, and you want to represent users without an age as a regular User
where age=null
. In this case, you could copy the Users and override the age field
// TODO: pass all the other fields too
val withoutAgeList = userList.map { User(it.name, null) }
Assuming Users
is a data class
, we can avoid explicitly naming all fields by making use of copy()
:
val withoutAgeList = userList.map { it.copy(age = null) }
Maybe the age property is nullable and mutable — and you actually want to change the users in place instead of copying them. This is somewhat risky and I don't advocate doing it this way unless you really know what you're doing though.
userList.forEach { it.age = null }
// They're actually the same list!
val withoutAgeList = userList
map
function – Nikolay Kulachenko