programming

Kotlin Variables and Data Types

Kotlin is a modern, concise, and type-safe programming language used for Android development, backend systems, desktop apps, and more. One of the core foundations of Kotlin is how it handles variables and data types. Understanding these is essential because they define how your program stores and manipulates information.

This post covers:

  • What variables are
  • Mutable vs immutable variables
  • Type inference
  • Kotlin’s built-in data types
  • Strings, arrays, collections
  • Null safety
  • Examples for each concept

Start learning Kotlin online

1. What is a Variable in Kotlin?

variable is a container that stores data in memory.

In Kotlin, you define a variable using two keywords:

  • val → immutable (cannot be changed)
  • var → mutable (can be changed)

Kotlin encourages immutability because it makes your code safer and more predictable.

2. Immutable Variables (val)

Use val when the value should not change after being assigned.

Example:

val name = "Luke"
val age = 30

Here:

  • name and age cannot be reassigned.
  • Trying to change them will produce a compilation error.

Immutability is best practice for most variables.

3. Mutable Variables (var)

Use var when the value needs to change.

Example:

var score = 10
score = 20   // ✔ allowed

Use var for variables like counters, states, and temporary values.

4. Type Inference in Kotlin

Kotlin is a statically typed language, meaning variable types are known at compile time.
However, you do not always need to specify the type because Kotlin can infer it.

Example:

val city = "Lagos"    // inferred as String
val temperature = 28  // inferred as Int

If you want, you can explicitly set the type:

val city: String = "Lagos"
val temperature: Int = 28

5. Kotlin Basic Data Types

Kotlin includes several built-in primitive data types, but unlike Java, they are all objects under the hood (no primitive vs wrapper distinction).

Numerical Types

Integer Types

TypeRange
Byte-128 to 127
Short-32,768 to 32,767
Int-2^31 to 2^31-1
Long-2^63 to 2^63-1

Example:

val count: Int = 100
val population: Long = 7_800_000_000

The underscore _ improves readability.

Floating-Point Types

TypePrecision
Float6-7 decimal digits
Double15-16 decimal digits

Example:

val percentage: Float = 99.5F
val pi: Double = 3.14159265358979

Note the F suffix for Float.

Character Type (Char)

Represents a single Unicode character.

val initial: Char = 'K'

Characters use single quotes.

Boolean Type (Boolean)

Stores logical values: true or false.

val isOnline: Boolean = true
val isSubscribed = false

6. Strings in Kotlin

Strings are sequences of characters enclosed in double quotes.

Example:

val name = "Lawson"

Kotlin also supports string templates, allowing you to insert variables directly:

val age = 25
println("My name is $name and I am $age years old.")

For expressions, use ${ }:

println("Next year I will be ${age + 1}")

Multi-line Strings

Use triple quotes """:

val message = """
    Hello Kotlin!
    Welcome to multiline strings.
""".trimIndent()

7. Arrays

An array stores multiple values of the same type.

Creating arrays:

val numbers = arrayOf(1, 2, 3, 4)
val names = arrayOf("Luke", "James", "Ada")

Access elements:

println(numbers[0])  // prints 1

Modify elements:

numbers[1] = 20

8. Kotlin Collections (Important)

Kotlin collections come in two major types:

Immutable Collections

  • listOf()
  • setOf()
  • mapOf()

Mutable Collections

  • mutableListOf()
  • mutableSetOf()
  • mutableMapOf()

Example:

val fruits = listOf("Apple", "Orange")         // cannot change
val numbers = mutableListOf(1, 2, 3)           // can change
numbers.add(4)

9. Kotlin Null Safety

Kotlin has built-in protection against null pointer exceptions.

By default, variables cannot hold null.

val name: String = "Luke"
// name = null  ❌ error

To allow null, you must add ?

Example:

var middleName: String? = null

You must safely handle nullable variables using:

  • ?. (safe call)
  • ?: (Elvis operator)
  • !! (non-null assertion – risky)

Example:

println(middleName?.length)   // safe call (returns null)
println(middleName ?: "N/A")  // Elvis (default value)

10. Type Conversion

Kotlin does not automatically convert between different types.

To convert:

val num = "123".toInt()
val amount = 45.toDouble()

Common conversion functions:

  • toInt()
  • toLong()
  • toFloat()
  • toDouble()
  • toString()

11. Putting It All Together (Example Program)

fun main() {

    val name: String = "Kotlin Student"
    var score: Int = 90

    val pi = 3.14      // inferred as Double
    val isActive = true

    var nickname: String? = null

    val numbers = mutableListOf(1, 2, 3)
    numbers.add(4)

    println("Name: $name")
    println("Score: $score")
    println("PI: $pi")
    println("Active: $isActive")
    println("Nickname: ${nickname ?: "No nickname"}")
    println("Numbers: $numbers")
}

Summary

ConceptExplanation
valImmutable variable
varMutable variable
Type inferenceKotlin automatically detects types
Basic TypesInt, Double, Boolean, Char, String
Nullable typesUse ? to allow null
CollectionsImmutable vs mutable lists, sets, maps
Type conversionManual conversions needed

Recent Posts

JavaScript Memoization

In JavaScript, it’s commonly used for: Recursive functions (like Fibonacci) Heavy calculations Repeated API/data processing…

7 days ago

CSS Container Queries: Responsive Design That Actually Makes Sense

For years, responsive design has depended almost entirely on media queries. We ask questions like: “If…

7 days ago

Cron Jobs & Task Scheduling

1. What is Task Scheduling? Task scheduling is the process of automatically running commands, scripts,…

7 days ago

Differences Between a Website and a Web App

Here’s a comprehensive, clear differentiation between a Website and a Web App, from purpose all the…

2 weeks ago

Essential VS Code Extensions Every Developer Should Use

Visual Studio Code (VS Code) is powerful out of the box, but its real strength…

4 weeks ago

JavaScript Variables

1. What Is a Variable in JavaScript? A variable is a named container used to store data…

4 weeks ago