kotlin for
时间: 2023-11-05 09:56:03 浏览: 37
Kotlin中的for循环可以使用不同的语法来实现。根据给出的代码示例,以下是三种不同的Kotlin for循环的写法:
1. 使用downTo关键字的降序循环:
```
for (i in 100 downTo 0) {
println(i) // 输出: 100 ~ 0
}
```
2. 使用zip函数实现同时遍历两个范围:
```
for ((i, j) in (0 until 100).zip(100 downTo 0)) {
println("i: $i, j: $j") // 输出: i: 0, j: 100 ~ i: 99, j: 1
}
```
3. 使用while循环的变体:
```
var i = 0
var j = 100
while (i < 100 && j > 0) {
println("i: $i, j: $j") // 输出: i: 0, j: 100 ~ i: 99, j: 1
i++
j--
}
```
相关问题
kotlin for in
在Kotlin中,可以使用for循环来遍历数组、集合和范围。下面是几个示例:
1. 遍历数组:
```kotlin
val array = arrayOf(1, 2, 3, 4, 5)
for (element in array) {
println(element)
}
```
2. 遍历集合:
```kotlin
val list = listOf("apple", "banana", "orange")
for (item in list) {
println(item)
}
```
3. 遍历范围:
```kotlin
for (i in 1..5) {
println(i)
}
```
在上述示例中,for循环会依次遍历数组、集合或范围中的每个元素,并将每个元素赋值给循环变量(例如`element`、`item`、`i`)。然后,您可以在循环体内对每个元素进行操作。
kotlin for Each
In Kotlin, the `forEach` function is used to iterate over a collection and perform an action on each element. Here's an example:
```kotlin
val numbers = listOf(1, 2, 3, 4, 5)
numbers.forEach { println(it) }
```
In the above code, `forEach` is called on the `numbers` list, and a lambda expression is passed as an argument. The lambda expression `{ println(it) }` is invoked for each element in the list, and it simply prints out each element.
You can replace `println(it)` with any other action you want to perform on each element.