Book Image

Programming Kotlin

Book Image

Programming Kotlin

Overview of this book

Quickly learn the fundamentals of the Kotlin language and see it in action on the web. Easy to follow and covering the full set of programming features, this book will get you fluent in Kotlin for Android.
Table of Contents (20 chapters)
Programming Kotlin
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Customer Feedback
Preface

Loops


Kotlin supports the usual duo of loop constructs found in most languages - the while loop and the for loop. The syntax for while loops in Kotlin will be familiar to most developers, as it is exactly the same as most C-style languages:

    while (true) { 
      println("This will print out for a long time!") 
    } 

The Kotlin for loop is used to iterate over any object that defines a function or extension function with the name iterator. All collections provide this function:

    val list = listOf(1, 2, 3, 4) 
    for (k in list) { 
      println(k) 
    } 
 
    val set = setOf(1, 2, 3, 4) 
    for (k in set) { 
      println(k) 
    } 

Note the syntax using the keyword in. The in operator is always used with for loops. In addition to collections, integral ranges are directly supported either inline or defined outside:

    val oneToTen = 1..10 
    for (k in oneToTen) { 
      for (j in 1..5) { 
        println...