Understanding Kotlin Variables: From Basics to Constants
Introduction and Lesson Overview
Welcome! Today, we're delving into Kotlin variables, which are critical elements in any programming language. They function as containers that store and handle data. In this lesson, we will explore what they are, learn about assigning values and assigning names to them, and discuss what constants are in Kotlin.
What are Variables in Kotlin?
A variable is a slot in memory that stores data, its content can change during the execution of the program. For example, in the snippet below, the value "Alice" held by myName is replaced by "Bob":
Kotlin has two types of variables - val, which is immutable, and var, which is mutable.
Declaring Variables in Kotlin
In Kotlin, you can reassign values to variables declared with var, but variables declared with val are immutable. Let's assign and reassign a value to myAge to see this in action:
Now, let's try to alter a constant, myBirthYear:
Kotlin Variable Naming Conventions
In Kotlin, we adhere to the camelCase naming convention, which helps deliver clear, purposeful names. Good examples include numberOfStudents, accountBalance, userDetails. Poor examples like c, xyz, temp lack clear purpose and should, therefore, be avoided.
Understanding Constants in Kotlin
Kotlin uses const val for constants, which are declared at the top level:
Constants are used for values that are not subject to change.
Basic String Interpolation in Kotlin
