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

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.

主站蜘蛛池模板: 松江区| 清镇市| 永清县| 松阳县| 翼城县| 连山| 墨江| 崇信县| 怀化市| 长宁区| 塘沽区| 宁都县| 屯门区| 郸城县| 白朗县| 奇台县| 麻栗坡县| 老河口市| 凉城县| 常州市| 金山区| 黑水县| 东阳市| 绵竹市| 龙川县| 遂宁市| 荆门市| 正阳县| 垦利县| 永年县| 阳西县| 双流县| 永仁县| 河南省| 东乡族自治县| 合水县| 兰坪| 南投县| 南丹县| 赤城县| 科尔|