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

Control flow as expressions


An expression is a statement that evaluates to a value. The following expression evaluates to true:

    "hello".startsWith("h")  

A statement, on the other hand, has no resulting value returned. The following is a statement because it assigns a value to a variable, but does not evaluate to anything itself:

    val a = 1 

In Java, the common control flow blocks, such as if...else and try..catch, are statements. They do not evaluate to a value, so it is common in Java, when using these, to assign the results to a variable initialized outside the block:

    public boolean isZero(int x) { 
      boolean isZero; 
      if (x == 0) 
        isZero = true; 
      else 
        isZero = false; 
      return isZero; 
    }

In Kotlin, the if...else and try..catch control flow blocks are expressions. This means the result can be directly assigned to a value, returned from a function, or passed as an argument to another function...