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?

A 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

Common React Errors

React makes building user interfaces easier, but certain errors appear repeatedly, especially when working with…

1 week ago

C Programming Cheat Sheet

The C programming language is a foundational, general-purpose computer programming language created by Dennis Ritchie at Bell Labs in 1972. Originally developed to…

1 week ago

Homebrew Tutorial

What Is Homebrew? Homebrew is a package manager for macOS and Linux that makes it easy to…

2 weeks ago

10 Ways to Loop Through a JavaScript Array

JavaScript gives you several ways to iterate over an array. Some are better for simple…

2 weeks ago

Build a Node JS Web Server

A web server is the software responsible for receiving requests from clients, processing those requests,…

2 weeks ago

Shell Prompt Tutorial

A shell prompt is the text displayed by a command-line shell to show that it is ready…

3 weeks ago