For each in kotlin10/10/2023 You may need to decipher that every time you come back to it. The indices/ mapIndexed-solution rather hide what's going on. It's way easier to read when you come back. And I can only recommend you to use the flatMap instead. Depending on how complex your condition is, the indices themselvses will not suffice you. We can even use the implicit labels that are the same name as the function to which the lambda is passed and we don’t have to define the label. The condition for it 3 passes and return for that condition only but not for 4 and 5. Note that if what you are trying to insert is static, solution with the indices is of course easier then the mapping I've presented above. The reason why 4 and 5 were printed is that the forEach loop was called for each and every value separately. It should be easy enough though to add that case. In Kotlin, the for loop works like the forEach. indexOf returns -1 or itemsToInsertAfterMatch = null). Generally, the for loop is used to iterate through the given block of code for the specified number of times. ![]() ![]() what is matched with what? and what is inserted when where?).Īll the above solutions did not yet deal with the case when an element wasn't found (e.g. If you do not must (and who forces you?), I wouldn't use such a construct. ![]() As you said you iterate over the list, maybe a flatMap is rather something for you (in this example I add "odd", "even" after elements that are odd/even): val list = listOf("1", "2", "3", "4")Ġ -> listOf(it, " listOf(it, " itemsToInsertAfterMatch?.let
0 Comments
Leave a Reply.AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |