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

Null syntax


Tony Hoare, the inventor of the quicksort algorithm, who introduced the concept of the null reference in 1965 called it his "billion dollar mistake". Unfortunately, we have to live with null references as they are present in the JVM, but Kotlin introduces some functionality to make it easier to avoid some common mistakes.

Kotlin requires that a variable that can assigned to null be declared with a ?:

    var str: String? = null 

If this is not done, the code will not compile. This next example would result in a compile time error:

    var str: String = null 

Kotlin has much more than this to help in the fight against null pointer exceptions, and there is a full discussion of nulls and null safety in Chapter 7, Null Safety, Reflection, and Annotations.

Type checking and Casting: If a reference to an instance is declared as some general type A, but we want to test if we have a more specific type B, then Kotlin provides the is operator. This is equivalent to the instanceof...