- Kotlin Ranges
- A simple example of Kotlin Ranges
- Check element in Ranges
- Kotlin Range: rangeTo() and downTo() functions
- Kotlin Range Step
- Kotlin range reverse
- Top Related Articles:
- About the Author
- Kotlin — Ranges and arrays
- Interval declaration
- Interval common operations
- Type of interval
- Array
- Create an array
- use Array Class create array
- Using library functions arrayOfXXX() Create an array
- Array of primitive data types
- Common operations on arrays
- rangeTo
- Ranges and progressions
- Progression
Kotlin Ranges
In this guide, we will discuss the very cool feature of Kotlin which is ranges. With the help of ranges in Kotlin we can easily create a list of sequence by specifying starting and ending value. For example a range of 1..5 would create a series of values 1, 2, 3, 4, 5. Similarly we can create character ranges such as ‘A’..’D’ which will create a series of values A, B, C, D. We can also create ranges in reverse order and several other things with ranges. Lets get started.
A simple example of Kotlin Ranges
In the following example, we have created two ranges, one is an integer range and other one is a character range. We are cycling through the elements of the ranges using for loop.
/** * created by Chaitanya for Beginnersbook.com */ package beginnersbook fun main(args : Array) < println("Number range:") for(num in 1..4)< println(num) >println("Character range:") for(ch in 'A'..'E') < println(ch) >>
Output:
Check element in Ranges
We can also check whether a particular element is present in the range or not. Lets see how to do this with the help of a simple example.
package beginnersbook fun main(args : Array)< val oneToTen = 1..10 println("3 in oneToTen: $") println("11 in oneToTen: $") >
3 in oneToTen: true 11 in oneToTen: false
Kotlin Range: rangeTo() and downTo() functions
Instead of .. we can use these functions rangeTo() and downTo(), rangeTo() is for increasing order and downTo() is for decreasing order.
/** * created by Chaitanya for Beginnersbook.com */ package beginnersbook fun main(args : Array) < val oneToFive = 1.rangeTo(5) val sixToThree = 6.downTo(3) println("rangeTo:") for(x in oneToFive)< println(x) >println("downTo") for(n in sixToThree) < println(n) >>
Output:
Kotlin Range Step
With the help of step() function we can define the interval between the values. By default the value of step is 1 so when we create range 1..10, it is 1, 2, 3. 10. However if we want a specific interval like 3 then we can define the range like this 1..10.step(3) this way the values would be 1 4 7 10. Lets take an example.
package beginnersbook fun main(args : Array) < val oneToTen = 1..10 val odd = oneToTen.step(2) for(n in odd)< println(n) >>
Kotlin range reverse
We can reverse a range in Kotlin using reversed() function.
/** * created by Chaitanya for Beginnersbook.com */ package beginnersbook fun main(args : Array) < val oneToFive = 1..5 for (n in oneToFive.reversed())< println(n) >>
Output:
Top Related Articles:
About the Author
I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.
Kotlin — Ranges and arrays
An interval is a mathematical concept that represents a range.
Interval declaration
Kotlin can use.. Or until to declare the interval:
val range: IntRange = 0.1024. // closed range [0,1024], including 1024 val rangeExclusive: IntRange = 0 until 1024 // half-open interval [0,1024], excluding 1024 val emptyRange: IntRange = 0.. -1 // empty interval [] Copy the code
Actually, the. The rangeTo() operator corresponds to a rangeTo() method in the Int class:
/** Creates a range from this value to the specified [other] value. */ public operator fun rangeTo(other: Byte): IntRange /** Creates a range from this value to the specified [other] value. */ public operator fun rangeTo(other: Short): IntRange /** Creates a range from this value to the specified [other] value. */ public operator fun rangeTo(other: Int): IntRange /** Creates a range from this value to the specified [other] value. */ public operator fun rangeTo(other: Long): LongRange Copy the code
Interval common operations
Determine whether an element is in the interval:
println(range.contains(50)) // true println(500 in range) // true Copy the code
The in keyword here corresponds to the contains() method in the IntRange class, so the above two lines are essentially the same.
Determine whether the interval is empty:
println(rangeExclusive.isEmpty()) // false println(emptyRange.isEmpty()) // true Copy the code
// Output: 0, 1, 2, 3. 1020, 1021, 1022, 1023, for (i in rangeExclusive) < print("$i,")>Copy the code
In and for can be used together to achieve the traversal effect of the interval.
Type of interval
All ranges are subclasses of ClosedRange, with IntRange being the most commonly used. In addition to IntRange, ClosedRange subclasses include LongRange, CharRange, etc.
Using CharRange as an example, we can also write an interval of 26 upper and lower case letters:
// a b c d e f g h i j k l m n o p q r s t u v w x y z val lowerRange: CharRange = 'a'.'z' // A B C D E F G H I J K L M N O P Q R S T U V W X Y Z val upperRange: CharRange = 'A'.'Z' Copy the code
Array
An Array has nothing to do with a Number. It’s a list of objects.
Create an array
There are generally two ways to create arrays:
use Array Class create array
Let’s look at the Array constructor:
public class ArrayT < /** * Creates a new array with the specified [size], where each element is calculated by calling the specified * [init] function. The [init] function returns an array element given its index. */ public inline constructor(size: Int.init: (Int) - T) . > Copy the code
To create an Array using Array, specify the element type (usually omitted), and pass two mandatory parameters: Array size and element initialization function init.
val array = ArrayString(5) < index - "No.$index" > println(array.size) / / 5 for (str in array) < // No.0 No.1 No.2 No.3 No.4 print("$str ")>Copy the code
When a function argument is the last parameter, you can write it outside the parentheses, which is Kotlin’s lambda notation, or you can write it inside the parentheses without lambda notation: Val array = array (5, );
Using library functions arrayOfXXX() Create an array
ArrayOfXXX () : arrayOfXXX() : arrayOfXXX(); arrayOfXXX() : arrayOfXXX(); arrayOfXXX() : arrayOfXXX();
val arrayOfString: ArrayString = arrayOf("我"."Yes"."LQR") val arrayOfHuman: ArrayHuman = arrayOf(Boy("Moderate"."Handsome"."Deep"), Girl("Tender"."Sweet"."Moving")) val arrayOfInt: IntArray = intArrayOf(1.3.5.7) val arrayOfChar: CharArray = charArrayOf('H'.'e'.'l'.'l'.'o'.'W'.'o'.'r'.'l'.'d') Copy the code
Note that arrays of objects of String or custom types are created using arrayOf(), whereas arrays of primitive data types are created using library functions such as intArrayOf(), charArrayOf(), and so on. Library functions such as intArrayOf() and charArrayOf() were created by Kotlin to avoid the overhead of basic data boxing, such as: IntArrayOf (1, 3, 5, 7) creates arrays of type IntArray, which corresponds to Java int[], and arrayOf(1, 2, 3, 4) creates arrays of type Array int . The corresponding value in Java is Integer[].
Array of primitive data types
To avoid unnecessary boxing and unboxing, the array of basic data types is customized:
Java | Kotlin |
---|---|
int[] | IntArray |
short[] | ShortArray |
long[] | LongArray |
float[] | FloatArray |
double[] | DoubleArray |
char[] | CharArray |
Note: IntArray and Array are completely different types and cannot be converted directly to each other! Kotlin also has special classes for representing arrays of native types with no boxing overhead: ByteArray, ShortArray, IntArray, and so on. These classes do not inherit from Array, but they share the same set of method attributes.
Learn more Kotlin array of relevant knowledge, please visit: www.kotlincn.net/docs/refere.
Common operations on arrays
We can use.size to get the array length, and use for-in to iterate through the array:
println(arrayOfInt.size) / / 4 for (int in arrayOfInt) < // 1 3 5 7 print("$int ")>Copy the code
Array defines the get and set functions (which are converted to [] by operator overloading convention), so we can use [] to get or modify elements in an Array:
println(arrayOfHuman[1]) // I have a gentle personality, a sweet face and a charming voice arrayOfHuman[1] = Boy(Moderate "1"."Handsome 1".1. "it") println(arrayOfHuman[1]) // I am a gentle, handsome man with a deep voice Copy the code
Note: a custom object type println () the default output is object address information, such as: com. Charylin. Kotlinlearn. Boy @ 7440 e464, need to rewrite the class toString () method to modify the output log content.
CharArray provides the joinToString() method, which is used to concatenate an array of characters into a string.
println(arrayOfChar.joinToString()) // H, e, l, l, o, W, o, r, l, d println(arrayOfChar.joinToString("")) // HelloWorld Copy the code
Arrays can be sliced using the slice() method:
println(arrayOfInt.slice(1.2.)) / / [3, 5] Copy the code
rangeTo
Creates a range from this Comparable value to the specified that value.
This value needs to be smaller than or equal to that value, otherwise the returned range will be empty.
import java.sql.Date import kotlin.test.assertFalse import kotlin.test.assertTrue fun main(args: Array) < //sampleStart val start = Date.valueOf("2017-01-01") val end = Date.valueOf("2017-12-31") val range = start..end println(range) // 2017-01-01..2017-12-31 println("Date.valueOf(\"2017-05-27\") in range is $") // true println("Date.valueOf(\"2018-01-01\") in range is $") // false println("Date.valueOf(\"2018-01-01\") !in range is $") // true //sampleEnd >
Creates a range from this Double value to the specified that value.
Numbers are compared with the ends of this range according to IEEE-754.
import java.sql.Date import kotlin.test.assertFalse import kotlin.test.assertTrue fun main(args: Array) < //sampleStart val range = 1.0..100.0 println(range) // 1.0..100.0 println("3.14 in range is $") // true println("100.1 in range is $") // false //sampleEnd >
Creates a range from this Float value to the specified that value.
Numbers are compared with the ends of this range according to IEEE-754.
import java.sql.Date import kotlin.test.assertFalse import kotlin.test.assertTrue fun main(args: Array) < //sampleStart val range = 1f..100f println(range) // 1.0..100.0 println("3.14f in range is $") // true println("100.1f in range is $") // false //sampleEnd >
Ranges and progressions
Kotlin lets you easily create ranges of values using the .rangeTo() and .rangeUntil() functions from the kotlin.ranges package.
- a closed-ended range, call the .rangeTo() function with the .. operator.
- an open-ended range, call the .rangeUntil() function with the .. < operator.
Ranges are particularly useful for iterating over for loops:
To iterate numbers in reverse order, use the downTo function instead of .. .
It is also possible to iterate over numbers with an arbitrary step (not necessarily 1). This is done via the step function.
Progression
The ranges of integral types, such as Int , Long , and Char , can be treated as arithmetic progressions. In Kotlin, these progressions are defined by special types: IntProgression , LongProgression , and CharProgression .
Progressions have three essential properties: the first element, the last element, and a non-zero step . The first element is first , subsequent elements are the previous element plus a step . Iteration over a progression with a positive step is equivalent to an indexed for loop in Java/JavaScript.
When you create a progression implicitly by iterating a range, this progression’s first and last elements are the range’s endpoints, and the step is 1.
To define a custom progression step, use the step function on a range.
The last element of the progression is calculated this way:
- For a positive step: the maximum value not greater than the end value such that (last — first) % step == 0 .
- For a negative step: the minimum value not less than the end value such that (last — first) % step == 0 .
Thus, the last element is not always the same as the specified end value.
Progressions implement Iterable , where N is Int , Long , or Char respectively, so you can use them in various collection functions like map , filter , and other.