diff --git a/core-kotlin/src/main/kotlin/com/baeldung/forEach/forEach.kt b/core-kotlin/src/main/kotlin/com/baeldung/forEach/forEach.kt new file mode 100644 index 0000000000..ef56009c71 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/forEach/forEach.kt @@ -0,0 +1,61 @@ +package com.baeldung.forEach + + +class Country(val name : String, val cities : List) + +class City(val name : String, val streets : List) + +class World { + + private val streetsOfAmsterdam = listOf("Herengracht", "Prinsengracht") + private val streetsOfBerlin = listOf("Unter den Linden","Tiergarten") + private val streetsOfMaastricht = listOf("Grote Gracht", "Vrijthof") + private val countries = listOf( + Country("Netherlands", listOf(City("Maastricht", streetsOfMaastricht), + City("Amsterdam", streetsOfAmsterdam))), + Country("Germany", listOf(City("Berlin", streetsOfBerlin)))) + + fun allCountriesIt() { + countries.forEach { println(it.name) } + } + + fun allCountriesItExplicit() { + countries.forEach { it -> println(it.name) } + } + + //here we cannot refer to 'it' anymore inside the forEach + fun allCountriesExplicit() { + countries.forEach { c -> println(c.name) } + } + + fun allNested() { + countries.forEach { + println(it.name) + it.cities.forEach { + println(" ${it.name}") + it.streets.forEach { println(" $it") } + } + } + } + + fun allTable() { + countries.forEach { c -> + c.cities.forEach { p -> + p.streets.forEach { println("${c.name} ${p.name} $it") } + } + } + } +} + +fun main(args : Array) { + + val world = World() + + world.allCountriesExplicit() + + world.allNested() + + world.allTable() +} + +