Kotlin Variables and Data Types

A variable is a named storage box in memory. You put a value in it, give it a name, and use that name later in your code. Data types tell Kotlin what kind of value lives inside the box.

val vs var — The Two Ways to Declare Variables

Kotlin gives you two keywords for creating variables:

  • val — the value cannot change after you set it (like a sealed envelope)
  • var — the value can change anytime (like a whiteboard)
val country = "India"    // Cannot change. country = "USA" would cause an error.
var score = 0            // Can change. score = 10 is allowed.

When to Use Which

Situation                        | Use
---------------------------------|------
Store a birth date               | val
Track a game score               | var
Save the app version number      | val
Count items in a shopping cart   | var

Always prefer val by default. Switch to var only when you know the value will change.

Kotlin Data Types

Every variable stores a specific kind of data. Kotlin has built-in types for numbers, text, and true/false values.

Number Types

Type       | Size    | Range                         | Example
-----------|---------|-------------------------------|--------------------
Byte       | 8-bit   | -128 to 127                   | val b: Byte = 100
Short      | 16-bit  | -32,768 to 32,767             | val s: Short = 500
Int        | 32-bit  | about -2 billion to 2 billion | val age: Int = 25
Long       | 64-bit  | very large numbers            | val dist: Long = 9_000_000L
Float      | 32-bit  | decimals (less precise)       | val temp: Float = 36.6f
Double     | 64-bit  | decimals (more precise)       | val pi: Double = 3.14159

Text and Boolean Types

Type       | Stores               | Example
-----------|----------------------|-------------------------------
String     | Text (words)         | val name: String = "Riya"
Char       | Single character     | val grade: Char = 'A'
Boolean    | true or false only   | val isOnline: Boolean = true

Type Inference — Kotlin Guesses the Type

You do not always have to write the type. Kotlin looks at the value and figures it out automatically.

val city = "Mumbai"     // Kotlin infers: String
val age  = 22           // Kotlin infers: Int
val price = 9.99        // Kotlin infers: Double
val active = true       // Kotlin infers: Boolean

This makes your code shorter without losing safety.

Type Annotation — Writing the Type Explicitly

Sometimes you want to be specific. Write the type after a colon following the variable name.

val temperature: Float = 98.4f
val itemCount: Int = 5
val username: String = "dev_rohan"

Diagram — Variable in Memory

Variable Declaration:
  val score: Int = 100

Memory Box:
┌───────────────────┐
│  Name:  score     │
│  Type:  Int       │
│  Value: 100       │
│  Mutable: No(val) │
└───────────────────┘

String Templates

You can embed a variable directly inside a string using the $ symbol.

val name = "Ananya"
val age = 20
println("My name is $name and I am $age years old.")
// Output: My name is Ananya and I am 20 years old.

For expressions inside strings, wrap them in curly braces:

val price = 50
println("After tax: ${price * 1.18}")
// Output: After tax: 59.0

Constants with const

Use const val for values that are fixed at compile time — meaning Kotlin replaces them with the actual value before the program runs. Constants must be at the top level or inside an object, and they must be a basic type like Int or String.

const val MAX_PLAYERS = 10
const val APP_NAME = "eStudy247"

Numeric Literals — Making Large Numbers Readable

Kotlin lets you use underscores inside numbers to improve readability.

val population = 1_400_000_000   // easier to read than 1400000000
val hexColor = 0xFF5733          // hex format for colors
val binaryFlag = 0b1010_1100     // binary format

Type Conversion

Kotlin does not automatically convert one number type to another. You must do it explicitly.

val x: Int = 5
val y: Long = x.toLong()       // Int → Long
val z: Double = x.toDouble()   // Int → Double
val s: String = x.toString()   // Int → String

This strictness prevents subtle bugs where a large number gets silently cut down to fit a smaller type.

Leave a Comment

Your email address will not be published. Required fields are marked *