The Programmers Guide To Kotlin - Control
Written by Mike James   
Tuesday, 27 June 2017
Article Index
The Programmers Guide To Kotlin - Control
If and When as Expressions
Kotlin's For Loop

The For loop

The Kotlin for loop is both much simpler and more sophisticated than the standard Java or C for loop. It doesn't make use of the idea of a start value, a finish value, and an increment. Instead it is a simple iterator through a finite set of things. The good news is that where this is reducible to a traditional for loop with index, this is what the compiler does, so there is no loss of efficiency. 

The general for loop is:

for( item in collection) {
 things to do
}

This, of course, leads us to the question of what sort of collections can be used in a for loop?

The simple answer is any object that has an iterator method that returns an object with a next and a hasNext method. 

For example, range expressions are iterable. 

A range expression is created using the rangeTo function which is also usable as the infix operator .. 

There is a range expression for each of the integral IntRange, LongRange and CharRange types. These are optimized in the sense that they are compiled to the traditional index based for loop. 

So for example:

for(i in 1..10){
        println(i)
    }

prints 1 to 10 as you would expect. As .. is just operator shorthand for the rangeTo function you can write this as:

for(i in 1.rangeTo(10) ){
        println(i)
    }

There are also downTo and step functions that can be used to modify the sequence. For example:

for(i in 10.downTo(1) ){
        println(i)
    }

prints 10 down to 1 and: 

for(i in 10.downTo(1).step(2) ){
        println(i)
    }

prints 10,8,6,4,2.

As downTo and step are defined as operators these loop are usually written:

for(i in 10 downTo 1 ){
        println(i)
    }

and: 

for(i in 10 downTo 1 step 2){
        println(i)
    }

Notice that step cannot be negative and so you have to control the direction of the loop using downTo, which essentially makes the step negative.

What about the most common form of for loop found in other languages such as Java?

For example

for(int i=0; i<10; i++){...

This loop generates index values of 0,1,2...9. That is, it doesn't generate the final value 10. This is a natural loop because when used to index an array, say, the final value can be set to the size of the array and the index range is correct, i.e. an array of size 10 has elements a[0] to a[9].

For loops over array elements in Kotlin don't have to use a range for the  index you can simply write:

for(i in array.indices){..

So there isn't as much reason for a loop that doesn't include its final value in Kotlin, but there is one.

Notice that:

for(i in 0..10){
        println(i)
    }

does include the final value of 10, but if you don't want it to you can use the until function. That is:

for(i in 0 until 10){
 println(i)
}

only prints 0, 1, 2.. 9 

There is more to say about Kotlin for loops in the chapters on arrays and on collections. The important point about the for loop is that you can use any class that implements the Iterable Interface in a simple for loop, but if you want to use step the class has to be a range which also defines the step function.  

Kotlin Control

The flow of control statements available in Kotlin are superficially similar to those found in Java, C/C++, C# and other similar languages.They are, however, significantly improved.

The danger is that if you are more familiar with another language you will continue to write control statements that are essentially closer to that other language than idiomatic Kotlin. It is important to keep in mind that Kotlin provides ways of writing control structures that are easier to understand and this should always be your number one goal, even before the goal of writing correct code!

If code is clear its incorrectness will be obvious. If it is unclear then it is only correct until someone tries to change it. 

 

Programmer's Guide To Kotlin Third Edition

kotlin3e360

You can buy it from: Amazon

Contents

  1. What makes Kotlin Special
  2. The Basics:Variables,Primitive Types and Functions 
  3. Control
         Extract: If and When 
  4. Strings and Arrays
  5. The Class & The Object
  6. Inheritance
  7. The Type Hierarchy
  8. Generics
  9. Collections, Iterators, Sequences & Ranges
        Extract: Iterators & Sequences 
  10. Advanced functions 
  11. Anonymous, Lamdas & Inline Functions
  12. Data classes, enums and destructuring
        Extract: Destructuring 
  13. Exceptions, Annotations & Reflection
  14. Coroutines
        Extract: Coroutines 
  15. Working with Java
        Extract: Using Swing
  16. Compose Multiplatform
        Extract: Compose Layout ***NEW!

<ASIN:B0D8H4N8SK>

 kotlinlogo

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.

 

Banner


Udacity Offers More AWS Scholarships
28/06/2024

Udacity has announced it is accepting applications for the next wave of 1,000 AWS AI & ML Scholarships. Any student over the age of 16 who self-identifies as under-served or under-represented in t [ ... ]



JetBrains Integrates Gemini Into AI Assistant
18/06/2024

JetBrains has integrated Google DeepMind's Gemini language model into its AI-powered coding tool, AI Assistant. AI Assistant will now use the combined power of Gemini and several of JetBrains' proprie [ ... ]


More News

kotlin book

 

Comments




or email your comment to: comments@i-programmer.info



Last Updated ( Tuesday, 27 June 2017 )