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

Ranges

A range is a way to define a sequence of values. It is denoted by the first and last value in the sequence. We can use ranges to store weights, temperatures, time, and age. A range is defined using double dot notation (under the hood, a range uses the rangeTo operator):

    val intRange = 1..4 // 1 
    val charRange= 'b'..'g' // 2 
  1. Inferred type is IntRange (equivalent of i >= 1 && i <= 4).
  2. Inferred type is CharRange (equivalent of letters from 'b' to 'g').
Notice that we are using single quotes to define the character range.

The Int, Long, and Char type ranges can be used to iterate over next values in the for... each loop:

    for (i in 1..5) print(i) // Prints: 1234 
    for (i in 'b'..'g') print(i) // Prints: bcdefg 

Ranges can be used to check a value is bigger than a start value and smaller than an end value:

    val weight = 52 
    val healthy = 50..75 
 
    if (weight in healthy) 
        println("$weight is in $healthy range") 
//Prints: 52 is in 50..75 range

It can be also used this way for other types of range, such as CharRange:

    val c = 'k'      // Inferred type is Char
    val alphabet = 'a'..'z'  
 
    if(c in alphabet) 
        println("$c is character") //Prints: k is a character 

In Kotlin, ranges are closed (end inclusive). This means that the range ending value is included in the range:

    for (i in 1..1) print(i) // Prints: 123

Note that ranges in Kotlin are incremental by default (a step is equal to 1 by default):

    for (i in 5..1) print(i) // Prints nothing 

To iterate in reverse order, we must use a downTo function, which sets a step to -1, as in this example:

    for (i in 5 downTo 1) print(i) // Prints: 54321 

We can also set different steps:

    for (i in 3..6 step 2) print(i) // Prints: 35 

Notice that in the 3..6 range, the last element was not printed. This is because the stepping index moves two steps in each of the loop iterations. So in the first iteration, it has a value of 3, in the second iteration a value of 5, and finally in a third iteration the value would be 7, so it is ignored, because it is outside the range.

A step defined by the step function must be positive. If we want to define a negative step, then we should use the downTo function together with the step function:

    for (i in 9 downTo 1 step 3) print(i) // Prints: 963 
主站蜘蛛池模板: 绥中县| 礼泉县| 三亚市| 镇康县| 普宁市| 郑州市| 手机| 英德市| 昔阳县| 唐河县| 泸溪县| 沙雅县| 莱阳市| 盐边县| 灵台县| 谢通门县| 尤溪县| 恩施市| 安化县| 唐河县| 肇州县| 绥滨县| 罗源县| 丹东市| 开化县| 农安县| 兴城市| 曲松县| 乃东县| 西充县| 沙坪坝区| 大悟县| 太湖县| 梅河口市| 临猗县| 加查县| 兴和县| 巩留县| 固镇县| 石景山区| 怀柔区|