Linux Format

Kotlin datatypes

In part two of his series on Kotlin, Mihalis Tsoukalos shows you how to use Kotlin arrays, lists, for and while loops with blocks and ranges.

-

Mihalis Tsoukalos shows you how to use Kotlin arrays, lists, for and while loops, with blocks and ranges, what else?

It’s time to get serious with Kotlin! We’re going to learn about two critical subjects: Kotlin Data Types and Control Flow, which includes arrays and lists as well as for, while and do-while loops. Additional­ly, you’ll learn more about ranges, exception handling and null safety. Soon you’ll be writing your own command line utilities in Kotlin!

Data types

Kotlin offers support for the standard data types: various types of integers, floats and doubles as well as boolean variables and strings. What’s key is that you can define two kinds of variables – mutable and immutable – which are declared using the var keyword and the val keyword, respective­ly. Note that immutable variables must be initialise­d when they’re created.

The screenshot ( above-right) shows the Kotlin code of dataTypes.kt where the use of Kotlin data types is illustrate­d in more detail. Because Kotlin has support for type inference, the compiler is able to “guess” the type of an expression without your help. However, you can still define the type of a variable if you want. If you compile and execute dataTypes. kt, you’ll produce the following output: $ java -jar dataTypes.jar i initial value: 10 i is now: 11 Equal! aLong = 1231234332

Control flow and looping

Time to cover control flow and looping in Kotlin, which includes the use of if, for, while and do...while. The if statement works as expected, but it also has some clever capabiliti­es: >>> var h = 10 >>> var myVariable = “It is " + if ( h < 12 ) { “Early” } else { “Late!” } >>> println(myVariable) It is Early So, you can include if statements in expression­s!

The next Kotlin block is executed in REPL and shows the use of the for loop in Kotlin using the values of a set: >>> val aSet = setOf(1, 2,5, 6, 8) >>> for (i in aSet) { print ("$i “) } 12568

Note that if a for loop has only one statement then there’s no need to use curly brackets. However, this approach can cause nasty bugs and should be avoided unless you really need that extra space. Additional­ly, the for loop works with every object that provides an iterator, similarly to the each for loop provided by other programmin­g languages.

The break keyword is used for exiting a for or a while loop, whereas the continue keyword is used for skipping the current iteration and moving on to the next one. The next REPL (ReadEval-Print Loop) shows the while statement in action: >>> println(i) 10 >>> while ( true ) { ... if ( i == 12 ) { break } ... i=i+1 ... println(i) ... } 11 12

One last thing: objects of the String class can be used inside for loops because they provide an iterator. The following Kotlin program, named countChar.kt, counts the characters of each one of its command line arguments: fun main(args: Array<String>) { if (args.size == 0) { println("Please give me at least one argument!") return } for (k in args) { var sum = 0 for (c in k) sum = sum + 1 println("$k has $sum characters.“) } } As you can see, countChar.kt uses two loops, one for visiting all command line arguments and another one for counting the characters of the input. Executing countChar.kt creates the following kind of output: $ kotlinc countChar.kt -include-runtime -d countChar.jar $ java -jar countChar.jar 123 12.3.4 abcd 123 has 3 characters. 12.3.4 has 6 characters. abcd has 4 characters. Here’s the do...while loop in the next interactio­n with REPL: >>> var i = 10 >>> do { println(i) } while ( i < 5 ) 10 The main difference between a do...while loop and the other two loops is that with a do...while loop you’re sure that you’ll get at least one iteration, which is handy when you want to initialise things. Although you can make for, while and do... while loops equivalent, do...while blocks of code are easier to read, which is the main reason for using them.

Hurray for arrays

Let’s dive into Kotlin array use. The following two statements create two identical arrays: >>> var a1 = arrayOf("1”, “4”, “9”, “16") >>> var a2 = Array(4, { i-> (i * i).toString()})

So, you’re able to use a function to create the elements of an array as it happens with a2. Strictly speaking, Array() is a constructo­r of the Array class that requires a size and a function that will be used for generating an array’s elements.

Consider the following commands that will be executed in the Kotlin REPL: >>> var strangeArr­ay = arrayOf(1, 0, “aString") >>> var thisWillNo­tWork = intArrayOf(1, 0, “aString") error: type mismatch: inferred type is String but Int was expected var thisWillNo­tWork = intArrayOf(1, 0, “aString")

The first statement shows that you can mix elements of various types in a Kotlin array. However, when you declare the type of the array, as it happens with thisWillNo­tWork, you can’t add elements of other types to that array.

Another handy method that can be applied to arrays is joinToStri­ng(). Here it is in action:

 ??  ??
 ??  ?? Here’s the code of dataTypes.kt, where the use of mutable and immutable variables is illustrate­d using easy-to-understand Kotlin statements.
Here’s the code of dataTypes.kt, where the use of mutable and immutable variables is illustrate­d using easy-to-understand Kotlin statements.
 ??  ?? Figure 2 shows the Kotlin code of usingArray­s.kt. It illustrate­s two ways to access all the elements of an array: using array.indices and array.size.
Figure 2 shows the Kotlin code of usingArray­s.kt. It illustrate­s two ways to access all the elements of an array: using array.indices and array.size.

Newspapers in English

Newspapers from Australia