📅  最后修改于: 2021-01-05 08:08:51             🧑  作者: Mango
Kotlin range实用程序功能具有在Kotlin range中使用的几个标准库函数。这些实用程序功能如下:
rangeTo()函数用于按范围中提到的升序从头到尾返回值。 rangeTo()函数是整数类型,它调用Range类的构造函数。
fun main(args: Array) {
var range: IntRange = 1.rangeTo(5)
println("Printing value: 1.rangeTo(5)")
for (x in range){
print("$x ")
}
println("")
var range2: IntRange = IntRange(1,5)
println("Printing value: IntRange(1,5)")
for (x in range2){
print("$x ")
}
}
输出:
Printing value: 1.rangeTo(5)
1 2 3 4 5
Printing value: IntRange(1,5)
1 2 3 4 5
像Double,Float这样的浮点数据类型(或多个数据类型)未在rangeTo运算符定义。
downTo()扩展函数用于按降序从高阶到低阶返回值。 downTo()函数是为一对整数类型定义的。
句法:
fun Long.downTo(other: Int): LongProgression {
return LongProgression.fromClosedRange(this, other.toLong(), -1L)
}
fun Byte.downTo(other: Int): IntProgression {
return IntProgression.fromClosedRange(this.toInt(), other, -1)
}
downTo()函数示例
fun main(args: Array) {
println("Range 1")
var range1 = 5 downTo 1
for (x in range1){
print("$x ")
}
println()
println("Range 2")
var range2: IntProgression = 5.downTo(1)
for (x in range2){
print("$x ")
}
println()
println("Range 3")
var range3: IntProgression = IntProgression.fromClosedRange(5,1,-1)
for (x in range3){
print("$x ")
}
}
输出:
Range 1
5 4 3 2 1
Range 2
5 4 3 2 1
Range 3
5 4 3 2 1
reversed()函数用于返回给定范围类型的逆序。
句法:
fun IntProgression.reversed(): IntProgression {
return IntProgression.fromClosedRange(last, first, -step)
}
fun main(args: Array) {
println("Reversed 1")
var range1 = 1..5
for (x in range1.reversed()){
print("$x ")
}
println()
println("Reversed 2")
var range2: IntRange = IntRange(1,5)
for (x in range2.reversed()){
print("$x ")
}
println()
println("Reversed 3")
var range3 = IntProgression.fromClosedRange(5,1,-1)
for (x in range3.reversed()){
print("$x ")
}
println()
println("Reversed 4")
var range4: IntProgression = IntProgression.fromClosedRange(5,1,-2)
for (x in range4.reversed()){
print("$x ")
}
}
输出:
Reversed 1
5 4 3 2 1
Reversed 2
5 4 3 2 1
Reversed 3
1 2 3 4 5
Reversed 4
1 3 5
step()函数(或step运算符)用于以给定step值的间隔返回范围值。步长值始终为正参数。负步进值将生成IllegalArgumentException异常。
fun main(args: Array) {
val range: IntRange = 1..10
println("Print range value with step 2:")
for(x in range step (2)){
print("$x ")
}
println("")
println("Print range value with step 3:")
for(x in range step 3){
print("$x ")
}
val first=((range step 2).first)
val last=((range step 2).last)
println("")
println("First value of interval: $first")
println("Last value of interval: $last ")
}
输出:
Print range value with step 2:
1 3 5 7 9
Print range value with step 3:
1 4 7 10
First value of interval: 1
Last value of interval: 9
如果我们将步进值提供为负整数,则会引发异常。
fun main(args: Array) {
val range: IntRange = IntRange(1,10)
for (x in range step -2){
print("$x ")
}
}
输出:
Exception in thread "main" java.lang.IllegalArgumentException: Step must be positive, was: -2.
at kotlin.ranges.RangesKt__RangesKt.checkStepIsPositive(Ranges.kt:130)
at kotlin.ranges.RangesKt___RangesKt.step(_Ranges.kt:432)
at TestKt.main(Test.kt:63)