From the course: Build Spring Boot Apps with the Kotlin Programming Language

Destructuring with a for loop

- [Instructor] Now there is one further thing we can do with this kind of loop, which is, well, if you remember we talked about when we created classes, the idea of destructuring, that is that if you're working with a data class or if you have built component and functions in a regular class, you can write code along the lines of this, we can do something like this. We could say, val, id, comma, title equals our content person and then we could use those say for example here print, line, dollars, person, has id, dollars, id. So that's this destructuring idea. Let's just run that to check that works. Okay, well that looks okay. Well, the thing we can do within a loop isn't rather than saying for person and people, we could do the destructure here. So we could say for, in brackets, id comma title comma first name. Let's get three this time in people. Then we can say print line, title, dollars, first name, has id, dollars, id. So we can do the destructuring as part of our for each loop. Let's just run that to prove that works. Okay, well that is working. That looks good, not that may not seem that useful at first but actually it can be very useful when we are working with maps. We will look at maps in more detail in the next chapter, but for now, I just want to change my array list into a hash map, so that we can see this looping structure. So rather than people being an array list, it's going to be a hash map and the key can be an integer and then we'll need to change this from added to port and we need to provide a key for each item so we'll use one, two, three, and four as the key. Okay, so we now have a hash map of common people with keys of one, two, three, and four. If I now want to do the looping through of the hash map, I can loop, getting out the key and the value and then we can print out each person's key. So this I think is quite nice when you are looping through a map, you can directly pull out the key and value as two separate local variables and then reference them within the code you are writing. So let's just run this and check if that works. Okay, that looks good. As I said, we will be talking a bit more about maps in the next chapter. But that's the idea for how we would loop through either a list or a map using the for each syntax.

Contents