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

Safe casting


Recall that, in Chapter 2 , Kotlin Basics, we introduced the as operator for casting a variable. If we want to safely cast to a type, or null if the cast would fail, then we can use the safe cast operator as?.

In the following example, we will cast a parameter that we know is a String, but the compiler doesn't know it is a String as we declared it as an Any:

    val location: Any = "London" 
    val safeString: String? = location as? String 
    val safeInt: Int? = location as? Int