官术网_书友最值得收藏!

The for loop

The for loop in Java, which prints each character of a string on a new line, may look something like this:

final String word = "Word";
for (int i = 0; i < word.length; i++) {

}

The same loop in Kotlin is:

val word = "Word";
for (i in 0..(word.length-1)) {
println(word[i])
}

Note that while the usual for loop in Java is exclusive (it excludes the last index by definition, unless specified otherwise), the for loop over ranges in Kotlin is inclusive. That's the reason we have to subtract one from the length to prevent overflow (string index out of range): (word.length-1).

If you want to avoid that, you can use the until function:

val word = "Word";
for (i in 0 until word.length) {
println(word[i])
}

Unlike some other languages, reversing the range indexes won't work:

val word = "Word";
for (i in (word.length-1)..0) {
println(word[i])
} // Doesn't print anything

If your intention is to print the word in reverse order, for example, use the downTo function:

val word = "Word";
for (i in (word.length-1) downTo 0) {
println(word[i])
}

It will print the following output:

d
r
o
W

It may seem confusing that until and downTo are called functions, although they look more like operators. This is another interesting Kotlin feature called infix call, which will be discussed later on.

主站蜘蛛池模板: 卢氏县| 酒泉市| 福泉市| 乌拉特中旗| 武冈市| 广灵县| 兴安县| 柳河县| 砚山县| 上栗县| 马龙县| 繁峙县| 垦利县| 新晃| 乐平市| 女性| 江门市| 抚远县| 扎囊县| 日土县| 上饶市| 福泉市| 清水县| 关岭| 平遥县| 漠河县| 彰武县| 闸北区| 大连市| 长春市| 阿瓦提县| 青铜峡市| 尉犁县| 塔城市| 双柏县| 巴彦县| 东光县| 阿坝县| 福海县| 潢川县| 固始县|