- Hands-On Design Patterns with Kotlin
- Alexey Soshin
- 231字
- 2021-06-25 20:49:25
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.
- Python自動(dòng)化運(yùn)維快速入門(mén)(第2版)
- Python自動(dòng)化運(yùn)維快速入門(mén)
- MATLAB 2020 從入門(mén)到精通
- 琢石成器:Windows環(huán)境下32位匯編語(yǔ)言程序設(shè)計(jì)
- TypeScript項(xiàng)目開(kāi)發(fā)實(shí)戰(zhàn)
- Haxe Game Development Essentials
- Node.js Design Patterns
- JavaScript腳本特效編程給力起飛
- 分布式數(shù)據(jù)庫(kù)原理、架構(gòu)與實(shí)踐
- Learning Android Application Testing
- JBoss AS 7 Development
- Building Web and Mobile ArcGIS Server Applications with JavaScript(Second Edition)
- INSTANT EaselJS Starter
- C#程序設(shè)計(jì)基礎(chǔ)與實(shí)踐
- ArcGIS Blueprints