Course Content
KOTLIN Tutorial
About Lesson

Declaring Variables

In the world of Kotlin programming, declaring variables is a fundamental aspect that every developer must grasp. Variables serve as containers for storing data, and Kotlin offers a concise and expressive syntax for declaring them. In this post, we’ll dive into the basics of declaring variables in Kotlin and explore the various ways to do so.

1. Variable Declaration Syntax

In Kotlin, declaring a variable is straightforward. You start with the keyword val or var, followed by the variable name and its data type, separated by a colon. Let’s look at a simple example:

val pi: Double = 3.14

Here, val indicates a read-only (immutable) variable, and var indicates a mutable variable. The data type Double specifies the type of the variable.

2. Type Inference

Kotlin is designed to be concise, and in many cases, you can omit the explicit data type thanks to type inference. The compiler can automatically deduce the type based on the assigned value. For example:

val name = "Kotlin"

In this case, Kotlin infers that the variable name is of type String.

3. Mutable vs. Immutable Variables

As mentioned earlier, you use val immutable variables and var for mutable ones. Immutable variables cannot be reassigned once initialized, providing a level of safety and predictability in your code.

val daysInWeek = 7 // Immutable variable
var counter = 0 // Mutable variable

4. Nullable Variables

Kotlin has a strong type system that distinguishes between nullable and non-nullable types. If a variable can hold a null value, you must explicitly declare it using the nullable type syntax.

val nullableString: String? = null

The ? after String indicates that nullableString can be assigned the value null.

5. Late-Initialized Variables

In certain scenarios, you might not be able to initialize a variable immediately. Kotlin provides the lateinit modifier for such cases, indicating that the variable will be initialized before its first usage.

lateinit var lateInitVariable: String

6. Constants

If you want to create a variable that behaves like a constant, you can use the const modifier. Note that const is applicable only to top-level or member-level val variables with a primitive type or String.

const val MAX_VALUE = 100