Linux Format

Arrays for primitive types

-

>>>1 + 4 println(a1.joinToStri­ng(”+ 9 + 16 + “)) >>> println(a1.joinToStri­ng(” +", “->”, “<-")) ->1+ 4 + 9 + 16<Look at the Kotlin code of usingArray­s.kt, which can be also seen in Figure 2 ( previouspa­ge), for more array examples. If you compile and execute usingArray­s.kt, you’ll get the following output: $ kotlinc usingArray­s.kt -include-runtime -d usingArray­s.jar $ java -jar usingArray­s.jar Size: 5 0 -2 3 100 2 0 1 2 1500 4

You can also create arrays with two dimensions. The next command creates an array with four rows and seven columns where the initial value of each one of its elements is -1: >>> var array2D = Array(4) { Array(7) { -1 } } You can access the first element of the array2D as follows: >>> array2D[0][0] -1 You can access all elements of a two dimensiona­l array using two for loops: for (r in array2D) { for (c in r) { print("$c “) } println() } Kotlin offers the ByteArray, CharArray, ShortArray, LongArray, IntArray, BooleanArr­ay, DoubleArra­y and FloatArray array implementa­tions for the primitive types. That’s a lot so we’ll illustrate the use of IntArray using intArray.kt, which can be seen in the screenshot below. Executing intArray.kt will generate the following output: $ kotlinc intArray.kt -include-runtime -d intArray.jar $ java -jar intArray.jar Size: 5 01234

Apart from the difference in the way you create an array, both IntArray() and arrayOf() return an Array object and provide the same methods for working with arrays. You can find the full list of methods at https://kotlinlang.org/api/ latest/jvm/stdlib/kotlin/-int-array/ and at https:// kotlinlang.org/api/latest/jvm/stdlib/kotlin/-array/. Kotlin also offers more advanced types of arrays that are objects of the Array<T> class where T is any data type.

So, the reasonable question is when to use the arrays that Kotlin offers and when to create your own. The answer is pretty simple: if what Kotlin offers suits your needs, use this for its speed because all data structures offered by a programmin­g language are faster than other implementa­tions. Otherwise, create your own array.

Lists

Kotlin has support for Lists, which are ordered collection­s. Apart from lists, the Kotlin standard library offers support for Maps, Sets, Arrays and Sequences, which are also collection­s – all of them are based on Java Collection Framework. This means that not everything that Kotlin offers is as naive as the two array types you saw in the two earlier sections.

You can create an immutable and a mutable list of integers as follows: var myList1 = listOf<Int>(0,1,2,3,4,5,6,7) var myList2 = mutableLis­tOf<Int>(0,1,2,3,4,5,6,7)

Figure 4 ( above) shows the Kotlin code of useLists.kt where you can learn more about how lists are used in Kotlin.

Compiling and executing useLists.kt will ouptut this: $ kotlinc useLists.kt -include-runtime -d useLists.jar $ java -jar useLists.jar 01234567 Index for value 4: 4 Index for value 14: -1 The size of the list: 8 Reversed: [1,7, 6, 5, 4, 3, 2, 1, -1, 0] Index for value 1: 2 Remove 1: true Remove 1: true Remove 1: false Reversed: [7,6, 5, 4, 3, 2, -1, 0]

The indexOf() method searches whether the given argument can be found in the list and returns its index or -1 if it wasn’t found on the list. Additional­ly, you can see that list elements are always printed in the same order and that the add() method enables you to add a new element to a list

either in the desired place or at the end of it. Lists can contain the same value multiple times – you can remove the first occurrence of a list element using the remove() method. If the element can be found multiple times on the list, you’ll have to call remove() multiple times.

Iterating with ranges

Earlier on in the Kotlin code of usingArray­s.kt, you saw the use of a range when we wanted to visit all elements of an array. Strictly speaking, a range is an interval with a start value and an end value. The good thing is that any comparable type can be used to generate a range.

There are many ways to customise a range, such as val zTo10 = 0..10 val step3 = zTo10.step(3) val down = 10.downTo(0) val reverse = (0..10).step(2).reversed()

The first range is created using the .. operator. The second range uses a step and the third range create a decreasing range. As there is no way to use a negative step value, the last example shows how you can use the reversed() method to create a decreasing range with a step.

You can test whether a given value is found in a range using the in operator: >>> println(1 in down) true >>> println(1 in step3) false

However, only integer ranges, which only includes int, long and char types, can be used in for loops. Look at this example where you use some of the ranges created earlier in this section in two for loops: >>> val myArray = Array(20, { i -> i }) >>> for (i in reverse) ... print("${myArray[i]} “) 10 8 6 4 2 0 >>> for (i in step3) ... print("${myArray[i]} “) 0369

Exception handling

Exception handling is a key feature of Kotlin that’s performed using try and catch blocks. Optionally, you can have a finally block at the end and multiple catch blocks to differenti­ate between exceptions.

In this section you’ll see a program named excHandle.kt that checks whether the given input is a valid integer or not. The program is using the toInt() function to show exception handing, which throws a NumberForm­atExceptio­n exception when the string you want to convert to an integer doesn’t have the right format. Note that the documentat­ion of each function should specify the names of the exceptions it throws as well as the reasons for throwing each of them. The screenshot ( above) shows the Kotlin code of excHandle.kt where you can see a try...catch block in action.

Executing excHandle.kt will create this kind of output: $ kotlinc excHandle.kt -include-runtime -d excHandle.jar $ java -jar excHandle.jar -2 123.2 a Got -2! Cannot convert 123.2 Cannot convert a

You can throw your own exceptions, which is mainly used in your own functions and methods, using the throw keyword.

There are two exercises that you might want to solve to see how well you understood the concepts of this tutorial. The first exercise is creating a program that keeps reading integers from the user until the user gives 0 as input. Then it prints the sum of all the integers it read. Try to implement it in three different ways: using a for loop, a while loop and a do while loop. The second one is creating a utility that checks whether the command line arguments of a program are valid integers or not and whether they are signed or unsigned.

 ??  ?? Figure 3 displays the Kotlin code of intArray.kt that shows how you can use the built-in IntArray data type to create an array of integers.
Figure 3 displays the Kotlin code of intArray.kt that shows how you can use the built-in IntArray data type to create an array of integers.
 ??  ?? Figure 4 shows the Kotlin code of useLists.kt that illustrate­s the use of Lists.
Figure 4 shows the Kotlin code of useLists.kt that illustrate­s the use of Lists.
 ??  ?? Here’s the Kotlin code of excHandle.kt that shows how to write a try and catch block to handle the NumberForm­atExceptio­n of the toInt() method.
Here’s the Kotlin code of excHandle.kt that shows how to write a try and catch block to handle the NumberForm­atExceptio­n of the toInt() method.

Newspapers in English

Newspapers from Australia