The Programmers Guide To Kotlin - Control
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

Now Available as a Print Book

cover

You can buy it from:

USA and World     Amazon.com
Canada            Amazon.ca

UK                Amazon.co.uk
France            Amazon.fr
Germany           Amazon.de
Spain             Amazon.es
Italy             Amazon.it

 

 

Contents
Some Chapters Already Available On The Web

  1. What makes Kotlin Special (Book Only)
  2. The Basics: Variables, Primitive Types and Functions
  3. Control
  4. Strings and Arrays
  5. The Class & The Object
  6. Inheritance
  7. The Type Hierarchy (Coming soon!)
  8. Generics
  9. Collections, Iterators, Sequences & Ranges
  10. Advanced functions **NEW!**
  11. Anonymous, Lamdas & Inline Functions
  12. Data classes, enums and destructuring
  13. Exceptions, Annotations & Reflection
  14. Working with Java

 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, FacebookGoogle+ or Linkedin.

 

Banner


Java EE Moving To Eclipse
14/09/2017

Java Enterprise Edition is moving to the Eclipse Foundation. The moved was announced by Oracle who made the decision with IBM and Red Hat. The three companies are the largest contributors to the platf [ ... ]



Is Your Degree Worth Its Cost?
20/09/2017

Reporting findings of a survey that some will find controversial, Stack Overflow suggests that developers are increasingly unlikely to recoup the cost of a university education. Stack Overflow urges t [ ... ]


More News

 
 

 

blog comments powered by Disqus



Last Updated ( Tuesday, 27 June 2017 )
 
 

   
Banner
RSS feed of all content
I Programmer - full contents
Copyright © 2017 i-programmer.info. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.