Arrays in Kotlin PDF
Document Details
Uploaded by ThrilledIridium
Minia University
Tags
Summary
This document explains how to create and use arrays in the Kotlin programming language. It provides examples demonstrating different ways to initialize and access array elements, highlighting Kotlin's array features and functionalities. The document also mentions exception handling and using the safe call operator for null checks, essential aspects for programming in general.
Full Transcript
Arrays Arrays are used to store multiple values in a single variable, instead of creating separate variables for each value. Kotlin doesn’t have an array object like the one created in Java using the square braces syntax. The Kotlin array is a generic class—it has a type parameter. We’ve...
Arrays Arrays are used to store multiple values in a single variable, instead of creating separate variables for each value. Kotlin doesn’t have an array object like the one created in Java using the square braces syntax. The Kotlin array is a generic class—it has a type parameter. We’ve been using Kotlin arrays for quite some time now because the small code snippets and the “Hello World” example in the previous chapter have featured the use of Arrays. The argument to the main function is actually an Array of String. Let’s see that main function again, just as a refresher. fun main(args:Array) { } There are a couple of ways to create an array: 1- They can be created using the arrayOf() 2- arrayOfNulls() functions, 3- and finally, they can be created using the Array constructor. 1-Creating array using arrayOf(): val num = arrayOf(1, 2, 3, 4) //implicit type declaration val num = arrayOf(1, 2, 3) //explicit type declaration Kotlin program of creating array using arrayOf() and arrayOf functions: fun main() { // declaring an array using arrayOf() val arrayname = arrayOf(1, 2, 3, 4, 5) for (i in 0..arrayname.size-1) { print(" "+arrayname[i]) } println() // declaring an array using arrayOf val arrayname2 = arrayOf(10, 20, 30, 40, 50) for (i in 0..arrayname2.size-1) { print(" "+arrayname2[i]) } } 2- Using the Array constructor: Since Array is a class in Kotlin, we can also use the Array constructor to create an array. The constructor takes two parameters: 1. The size of the array, and 2. A function which accepts the index of a given element and returns the initial value of that element. 3- Using the arrayOfNulls() The Kotlin arrayOfNulls() function is used to create an array of a specified size with all elements initialized to null for later assignment or when you want to initialize an array with nullable elements. fun main() { val nullArray = arrayOfNulls(5) for (element in nullArray) { println(element) } } Access the Elements of an Array You can access an array element by referring to the index number, inside square brackets. In this example, we access the value of the first element in cars: val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda") println(cars) // Outputs Volvo Array Length / Size To find out how many elements an array have, use the size property: Example: val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda") println(cars.size) // Outputs 4 Check if an Element Exists: You can use the in operator to check if an element exists in an array: fun main() { val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda") if ("Volvo" in cars) { println("It exists!") } else { println("It does not exist.") }} Loop Through an Array: Often when you work with arrays, you need to loop through all of the elements. You can loop through the array elements with the for loop, which you will learn even more about in the next chapter. The following example outputs all elements in the cars array: fun main() { val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda") for (x in cars) { println(x) } } Program Example: fun main(args: Array) { var emptyArray = arrayOfNulls(2) ➊ emptyArray = "Hello" ➋ emptyArray = "World" for (i in emptyArray.indices) println(emptyArray[i]) ➌ for (i in emptyArray) println(i) ➍ Comments: ➊ We used the arrayOfNulls function to create an array ➊ We used the arrayOfNulls function to create an array that has two that has two elements. elements. ➋➋WeWecancan assign assign valuesvalues to specific to specific elementselements of the of the array. We just need array.the specify We just need position of thespecify elementthe position in the of the array using its index. This syntax of accessing the element of the array is the same as in Java. element in the array using its index. This syntax of ➌ We can use the for loop to traverse the contents of the array. In this accessing the element of the array is the same as in example, we used the indices to access the element of the array. Java. ➍ This is a more direct way of accessing the element of the array. An ➌ We Array canhas object useanthe for loop iterator, so weto traverse can use thatthe contents iterator ofthe to get to theelement array array. In this right example, we used the indices to access away. the element of the array. ➍ This is a more direct way of accessing the element of the array. An Array object has an iterator, so we can use that iterator to get to the array element right away. Exception Handling Kotlin’s exception handling is very similar to Java: it also uses the try- catch-finally construct. However, Kotlin simplifies exception handling by simply using unchecked exceptions. What that means is writing try-catch blocks is now optional. You may or mayjava.io.FileReader import not do it. ➊ fun main(args: Array) { var fileReader = FileReader("README.txt") ➋ var content = fileReader.read() ➌ println(content) } ➊ We can use Java’s standard library in Kotlin. ➋ This one may throw the "FileNotFoundException". ➌ And this could throw the "IOException", but Kotlin happily lets us code without handling the possible Exceptions that may be thrown. Program Example: import kotlin.ArithmeticException fun main(args : Array) { var x = 10 var y = 3 try { println("10/3: " + x/y) x = 10 y=0 println("10/0: " + x/y) } catch(e: ArithmeticException){ // caught and handles it println("Divide Kotlin programby zero ofexception") } } using try-catch as an expression: Output: 3 java.lang.ArithmeticException: / by zero Divide by zero exception occurred Handling Nulls: In Kotlin, when we declare a variable like: var str: String = "Hello" str = null // won't work we will never be able to set the value of this variable to null. We may assign it a different String value, but Kotlin guarantees that str will never be null. If, for some reason, you really need this variable to be null, you have to explicitly tell Kotlin that str is a Nullable type. To make a String (or any type) Nullable, we use the question mark symbol as postfix to the type, like var str: String? = "Hello" For non-Nullable types: Kotlin ensures that it’s pretty safe to use them in operations such as assignment, printing, inclusion in expressions, etc. When we make types Nullable, Kotlin assumes that we know what we’re doing and that we’re responsible enough to write the necessary guard conditions to prevent NullPointerExceptions. Demonstration of Nullable Types fun main(args: Array) { var a = arrayOf(1,2,3) printArr(null) } fun printArr(arr: Array?) { ➊ if(arr != null) { ➋ arr.forEach { i -> println(i) } ➌ } } ➊ We’re declaring Array to be Nullable. This means we can pass null to printArr(). ➋ Because arr is no longer guaranteed to be non-null, we have to manually check for null values before we do some operations that involve the arr local variable. ➌ If arr is not null, we can safely perform this operation. Safe Call Operator: Kotlin introduced an operator that we can use to handle Nullable types. It’s called the safe-call operator, which is written as the question mark symbol followed by a dot ?. We can replace the entire if block, which performs the null checking, with just one statement: fun main(args: Array) { var a = arrayOf(1,2,3) printArr(null) } fun printArr(arr: Array?) { arr?.forEach { i -> println(i) } } Example: package com.includehelp.basic //Main Function, entry Point of Program fun main(args: Array) OutPut: {String s1 is isNullOrEmpty : true String s2 is isEmpty : true String s3 is ///Nullable isBlank : true String val s1: String?=null //Empty String val s2: String="" //Blank String, Contained only white spaces val s3=" " println("String s1 is isNullOrEmpty : ${s1.isNullOrEmpty()}") println("String s2 is isEmpty : ${s2.isEmpty()}") println("String s3 is isBlank : ${s3.isBlank()}") } OutPut: String s1 is isNullOrEmpty : true String s2 is isEmpty : true String s3 is isBlank : true