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

Ranges

A range is defined as an interval that has a start value and an end value. Any types which are comparable can be used to create a range, which is done using the .. operator:

    val aToZ = "a".."z" 
    val oneToNine = 1..9 

Once a range is created, the in operator can be used to test whether a given value is included in the range. This is why the types must be comparable. For a value to be included in a range, it must be greater than or equal to the start value and less than or equal to the end value:

    val aToZ = "a".."z" 
    val isTrue = "c" in aToZ 
  
    val oneToNine = 1..9 
    val isFalse = 11 in oneToNine 

Integer ranges such as (ints, longs, and chars) also have the ability to be used in a for loop. See the Loops section for further details.

There are further library functions to create ranges not covered by the .. operator; for example, downTo() will create a range counting down, and rangeTo()will create a range up to a value. Both of these functions are defined as extension functions on numerical types:

    val countingDown = 100.downTo(0) 
    val rangeTo = 10.rangeTo(20) 

Once a range is created, you can modify the range, returning a new range. To modify the delta between each successive term in the range, we can use the step() function:

    val oneToFifty = 1..50 
    val oddNumbers = oneToFifty.step(2) 

You cannot use a negative value here to create a decreasing range. Finally, ranges can be reversed using the reversed() function. As the name implies, it returns a new range with the start and end values switched, and the step value negated:

    val countingDownEvenNumbers = (2..100).step(2).reversed() 
主站蜘蛛池模板: 镇雄县| 东阿县| 郸城县| 玉门市| 太和县| 武鸣县| 新泰市| 灵寿县| 荥阳市| 双桥区| 广水市| 五大连池市| 都兰县| 盘山县| 莒南县| 镇宁| 望奎县| 马尔康县| 平陆县| 兴国县| 思南县| 宕昌县| 银川市| 霍林郭勒市| 舞阳县| 大渡口区| 晴隆县| 凯里市| 杂多县| 静宁县| 平南县| 宣汉县| 孝昌县| 蒲城县| 和平县| 突泉县| 德兴市| 广河县| 浑源县| 遂昌县| 法库县|