What's the idiomatic way to : if I have a listOf&l...
# announcements
p
What's the idiomatic way to : if I have a listOf<String>(...) and then I map it to a listOf<MyUiClass> to once I have this listOf<MyUiClass> remove an item of it if let's say today == whatever. Pseudo : val myList = listOf<String>("example1","example2",...) val mappedUiClass = myList.map{myMapper.map(it)} //Here I'd like to remove one exactly item if a condition is true. So for instance if mappedUiClass contains {id=1,name="Jhon", type: "MyType1"} {id=2,name="Hual", type: "MyType2"} {id=3,name="Hjdu", type: "MyType3"} If the condition is true I just want to keep in mappedUiClass the id1 and id3, so if condition == true remove MyType2.
d
Copy code
myList.mapNotNull { s -> myMapper.map(s).takeIf { it.type != "MyType2 } }
2
p
But here's meesing the condition. The condition would be like if(today.isRaining()) then remove the item that the type is MyType2
d
myList.mapNotNull { s -> myMapper.map(s).takeUnless { today.isRaining() && it.type == "MyType2 } }
p
Can not do the it.type inside the takeUnless
d
wdym "can not do"? Whats the error?
p
the it is the list<UiClass>
d
Can you show the actual code oyu tried?
p
sure
Copy code
val listString = getListOfStrings()
val listUi = listString.map{it.map(it)}.takeUnless { today.isRaining()}
This is not complaining
But then when I try to get the type it says that it is a list instead of the item itself
d
it.map(it)
that doesn't make sense 😄
p
note that it.map(it) is like extension function
Is doing the job, don't worry
Didn't want to put more things
d
You need
mapNotNull
and inside the
mapNotNull
you need
takeUnless
Your code looks nothing like what I posted...
val listUi = listString.mapNotNull { it.map(it).takeUnless { /* condition */ } }
p
I just want you to know that inside of val listUi there's the list mapped already so it's a listOf<Ui> instead of listOf<String>
d
Yes but you want listUi to be filtered, no?
You don't want an element in listUi for all elements in listString
You just want some
p
Oh wait
the takeUnless
is inside the map...
Right?
d
Yes
p
That's why I was getting the list...
Ok, let me try
d
hence mapNotNull, so it ignores everything that doesnt match the condition
p
yes
Thanks looks like is working 😛