Logo
Kotlin Basics
Kotlin BasicsVariables and Constants

Variables and Constants

Understanding variables and read-only variables in Kotlin, including their declaration, initialization, and usage.

In Kotlin, variables are used to store data that can be manipulated throughout the program. Kotlin provides two types of variables: mutable (var) and read-only (val). Mutable variables can be changed after their initial assignment, while read-only variables cannot. In this section, we'll explore both types, their syntax, and how to use them effectively.

Mutable Variables (var)

Mutable variables are declared using the var keyword. Once declared, their value can be changed.

Syntax

var variableName: DataType = initialValue

Example

var age: Int = 25
age = 26  // Allowed

Read-Only Variables (val)

Read-only variables are declared using the val keyword. They can be assigned a value only once.

Syntax

val constantName: DataType = value

Example

val pi: Double = 3.14159
// pi = 3.14  // Not allowed, will result in a compilation error

Type Inference

Kotlin has a powerful type inference system, which often allows you to omit the data type when declaring a variable.

Example

var name = "John"  // Type inferred as String
val isTrue = true  // Type inferred as Boolean

Nullability

In Kotlin, variables are non-nullable by default. To make a variable nullable, append a ? to its type.

Example

var nullableVar: String? = null
val nullableVal: Int? = null

Summary and Best Practices

  • Use val for variables whose value won't change to make the code more predictable.
  • Use var only when you need to modify the variable's value.
  • Leverage type inference but specify the type explicitly for better code readability when necessary.
  • Always prefer non-nullable variables and only use nullable types when required.

By understanding the difference between var and val, and how to use them effectively, you'll write more robust and maintainable Kotlin code, especially for Android Native development.

Book a conversation with us for personalize training today!

Was this helpful?
Logo