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

Vals and vars


Kotlin has two keywords for declaring variables, val and var. The var is a mutable variable, which is, a variable that can be changed to another value by reassigning it. This is equivalent to declaring a variable in Java:

    val name = "kotlin" 

In addition, the var can be initialized later:

    var name: String 
    name = "kotlin" 

Variables defined with var can be reassigned, since they are mutable:

    var name = "kotlin" 
    name = "more kotlin" 

The keyword val is used to declare a read-only variable. This is equivalent to declaring a final variable in Java. A val must be initialized when it is created, since it cannot be changed later:

    val name = "kotlin" 

A read only variable does not mean the instance itself is automatically immutable. The instance may still allow its member variables to be changed via functions or properties, but the variable itself cannot change its value or be reassigned to another value.