BAEL-2217 forEach within forEach (#6166)
This commit is contained in:
parent
98c9d22151
commit
af9a60bddf
61
core-kotlin/src/main/kotlin/com/baeldung/forEach/forEach.kt
Normal file
61
core-kotlin/src/main/kotlin/com/baeldung/forEach/forEach.kt
Normal file
@ -0,0 +1,61 @@
|
|||||||
|
package com.baeldung.forEach
|
||||||
|
|
||||||
|
|
||||||
|
class Country(val name : String, val cities : List<City>)
|
||||||
|
|
||||||
|
class City(val name : String, val streets : List<String>)
|
||||||
|
|
||||||
|
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<String>) {
|
||||||
|
|
||||||
|
val world = World()
|
||||||
|
|
||||||
|
world.allCountriesExplicit()
|
||||||
|
|
||||||
|
world.allNested()
|
||||||
|
|
||||||
|
world.allTable()
|
||||||
|
}
|
||||||
|
|
||||||
|
|
Loading…
x
Reference in New Issue
Block a user