Kotlin

Kotlin Variables and Data Types Explained: Complete Beginner’s Guide

If you are learning Kotlin for the first time, one of the first concepts you need to understand is variables and data types. Variables are used to store…

D
DevByteTechnical Author
Published
16 min read3 views
Kotlin Variables and Data Types Explained featuring val, var, String, Int, Double, Boolean, Char, and simple Kotlin code examples

Every programming language needs a way to store and work with information. Whether you are building an Android application, developing a backend service, or writing a simple program, you need variables to store values such as names, numbers, prices, and user information.

In Kotlin, variables and data types are fundamental concepts that every beginner should understand.

Kotlin is a modern, statically typed programming language developed by JetBrains. It is widely used for Android development and can also be used for backend development, server-side applications, and multiplatform projects.

One of Kotlin's most useful features is its ability to infer data types automatically while still providing strong type safety.

In this guide, you will learn:

  • What variables are in Kotlin.

  • The difference between val and var.

  • How Kotlin's type inference works.

  • The basic data types available in Kotlin.

  • How nullable and non-nullable types work.

  • How to convert between data types.

  • How to work with strings and collections.

  • Common mistakes beginners should avoid.

Let's start with the basics.

What Is a Variable in Kotlin?

A variable is a named location used to reference a value in a program.

For example, suppose you want to store a user's name and age in a Kotlin application.

fun main() {
    val name = "Rahul"
    val age = 25

    println(name)
    println(age)
}

Output:

Rahul
25

In this example:

  • name stores the string "Rahul".

  • age stores the integer 25.

  • println() displays the values in the console.

Kotlin automatically identifies the types of these variables based on their initial values.

The name variable is inferred to be a String, while age is inferred to be an Int.

You can also specify the data types explicitly.

fun main() {
    val name: String = "Rahul"
    val age: Int = 25

    println("Name: $name")
    println("Age: $age")
}

Both examples work correctly.

Kotlin's type system helps catch many type-related errors during compilation rather than waiting until the program runs.

Understanding val and var in Kotlin

Kotlin provides two main keywords for declaring variables:

  • val

  • var

Although both can be used to declare variables, they behave differently.

1. What Is val in Kotlin?

The val keyword declares a read-only variable reference.

Once a val variable has been initialized, you cannot assign a different value to that reference.

Example:

fun main() {
    val name = "Rahul"

    println(name)
}

Output:

Rahul

Now consider this example:

fun main() {
    val age = 25

    age = 26 // Compilation error
}

This code produces a compilation error because age is declared using val.

You cannot reassign a new value to it.

When should you use val?

Use val when a variable does not need to be reassigned after initialization.

For example:

val appName = "CodeByte"
val taxRate = 0.18
val country = "India"

Using val by default makes code easier to reason about because the references cannot accidentally be reassigned.

However, val does not automatically make the object itself immutable. It prevents reassignment of the reference, not necessarily changes to the object's internal state.

2. What Is var in Kotlin?

The var keyword declares a variable that can be reassigned.

Example:

fun main() {
    var age = 25

    println(age)

    age = 26

    println(age)
}

Output:

25
26

Because age is declared using var, you can assign a new value to it.

The new value must be compatible with the variable's declared or inferred type.

For example:

var score = 80

score = 95

This works because both values are integers.

However, this does not work:

var score = 80

score = "Excellent" // Compilation error

The variable was inferred to be an Int, so assigning a String is not allowed.

Difference Between val and var

Feature

val

var

Reassignment

Not allowed

Allowed

Type safety

Yes

Yes

Type inference

Supported

Supported

Typical use

Values that should not be reassigned

Values that need to change

Recommended default

Yes

When reassignment is required

Best practice: Prefer val unless your program genuinely needs reassignment.

What Are Data Types in Kotlin?

A data type defines the kind of value a variable can hold and the operations that can be performed on that value.

For example, a person's age is usually represented by an integer, while their name is represented by a string.

Kotlin is a statically typed language. This means variable types are determined during compilation, either explicitly or through type inference.

Kotlin's commonly used types include:

  • Int

  • Long

  • Short

  • Byte

  • Double

  • Float

  • Boolean

  • Char

  • String

Let's explore them individually.

1. Integer Types in Kotlin

Kotlin provides several integer types for representing whole numbers.

Int

Int is the most commonly used integer type.

fun main() {
    val age: Int = 25
    val quantity: Int = 100
    val temperature: Int = -10

    println(age)
    println(quantity)
    println(temperature)
}

An Int is a signed 32-bit integer.

Its range is:

-2,147,483,648 to 2,147,483,647

Use Int for values such as ages, quantities, and counters when the range is sufficient.

Long

Long is a signed 64-bit integer.

It is useful when you need to represent larger whole numbers.

fun main() {
    val population: Long = 8_000_000_000L

    println(population)
}

Output:

8000000000

The L suffix indicates a Long literal.

Kotlin also allows underscores in numeric literals to improve readability.

For example:

val accountNumber = 1_234_567_890L

Short

Short is a signed 16-bit integer.

fun main() {
    val temperature: Short = 250

    println(temperature)
}

Its range is:

-32,768 to 32,767

Short is less common in ordinary application code than Int.

Byte

Byte is a signed 8-bit integer.

fun main() {
    val level: Byte = 100

    println(level)
}

Its range is:

-128 to 127

It can be useful when working with binary data or APIs that specifically require byte values.

2. Floating-Point Types in Kotlin

Floating-point types represent numbers with fractional parts.

Kotlin provides Float and Double.

Double

Double is a 64-bit floating-point type and is generally the default choice for decimal numeric literals.

fun main() {
    val price = 499.99
    val height = 5.9

    println(price)
    println(height)
}

Kotlin infers both variables as Double.

You can also declare the type explicitly:

val distance: Double = 1500.75

Important: Binary floating-point types cannot represent every decimal fraction exactly. For financial calculations that require precise decimal arithmetic, consider an appropriate decimal representation such as BigDecimal on the JVM.

Float

Float is a 32-bit floating-point type.

To declare a Float literal, use the f or F suffix.

fun main() {
    val temperature: Float = 36.6f

    println(temperature)
}

Without the suffix, a decimal literal such as 36.6 is normally inferred as Double.

Example:

val price = 99.99       // Double
val temperature = 36.6f // Float

Use Float when a specific API requires it or when its reduced precision and storage characteristics are appropriate.

3. Boolean Type in Kotlin

The Boolean type represents logical values.

It has two possible values:

  • true

  • false

Example:

fun main() {
    val isLoggedIn: Boolean = true
    val isAdmin: Boolean = false

    println(isLoggedIn)
    println(isAdmin)
}

Output:

true
false

Booleans are commonly used in conditional statements.

fun main() {
    val age = 20

    val canVote = age >= 18

    if (canVote) {
        println("You are eligible to vote.")
    } else {
        println("You are not eligible to vote.")
    }
}

Output:

You are eligible to vote.

The expression age >= 18 evaluates to a Boolean.

4. Char Type in Kotlin

The Char type represents a single character.

Character literals use single quotation marks.

fun main() {
    val grade: Char = 'A'
    val initial: Char = 'R'

    println(grade)
    println(initial)
}

Output:

A
R

A Char is different from a String.

val letter: Char = 'A'
val word: String = "A"

The first value is a character, while the second is a string containing one character.

You can also use escape sequences.

val newline = '\n'
val tab = '\t'
val apostrophe = '\''

These represent a newline, a tab, and an apostrophe.

5. String Type in Kotlin

A String represents a sequence of characters.

Strings are one of the most frequently used types in Kotlin.

Example:

fun main() {
    val name: String = "Rahul"
    val language: String = "Kotlin"

    println(name)
    println(language)
}

Output:

Rahul
Kotlin

String Templates

Kotlin supports string templates, which allow you to insert variables and expressions directly into strings.

fun main() {
    val name = "Rahul"
    val age = 25

    println("My name is $name and I am $age years old.")
}

Output:

My name is Rahul and I am 25 years old.

Use $variableName to insert a variable.

For expressions, use ${expression}.

fun main() {
    val a = 10
    val b = 20

    println("Sum: ${a + b}")
}

Output:

Sum: 30

String templates help make Kotlin code concise and readable.

Multiline Strings

Kotlin supports multiline strings using triple quotation marks.

fun main() {
    val message = """
        Welcome to Kotlin.
        Learn variables and data types.
        Start building applications.
    """.trimIndent()

    println(message)
}

This is useful when storing multiline text without manually inserting newline escape sequences.

6. The Any Type in Kotlin

Any is the common supertype of all non-nullable Kotlin types.

It can hold values of different types, although the compiler treats a value declared as Any according to the operations available on Any until you perform a suitable type check or cast.

Example:

fun main() {
    val value: Any = "Hello Kotlin"

    println(value)
}

You can also use Any with other types:

val name: Any = "Rahul"
val age: Any = 25
val isActive: Any = true

However, you should not use Any everywhere.

Prefer specific types whenever possible because they make code easier to understand and allow the compiler to catch more errors.

7. The Unit Type in Kotlin

Unit represents the absence of a meaningful return value.

It is similar to void in languages such as Java and C.

For example:

fun greet(): Unit {
    println("Hello, Kotlin!")
}

You can also omit the return type because Kotlin infers Unit for a function that does not return a meaningful value.

fun greet() {
    println("Hello, Kotlin!")
}

Both functions serve the same purpose.

In everyday Kotlin code, you generally do not need to write : Unit explicitly.

8. The Nothing Type in Kotlin

Nothing represents a value that never exists because the expression cannot complete normally.

It is commonly used for functions that always throw an exception or never return.

Example:

fun fail(message: String): Nothing {
    throw IllegalStateException(message)
}

The function throws an exception and does not return normally.

Nothing is useful when the compiler needs to understand that a particular execution path cannot continue.

Beginners do not need to use it frequently, but recognizing the type can help when reading advanced Kotlin code.

Kotlin Type Inference

One of Kotlin's convenient features is type inference.

Type inference allows the compiler to determine a variable's type from its initial value.

For example:

fun main() {
    val name = "Rahul"
    val age = 25
    val price = 99.99
    val isActive = true

    println(name)
    println(age)
    println(price)
    println(isActive)
}

The compiler infers these types:

Variable

Value

Inferred Type

name

"Rahul"

String

age

25

Int

price

99.99

Double

isActive

true

Boolean

You don't need to specify every type manually.

However, you can still declare a type explicitly when it improves readability or when the type cannot be inferred from the declaration.

Example:

val age: Int = 25

Both approaches are valid.

Can You Declare a Variable Without Initializing It?

Yes, but the compiler needs enough information to determine the variable's type.

For example:

fun main() {
    var message: String

    message = "Hello Kotlin"

    println(message)
}

Here, the type is explicitly declared.

Kotlin also supports definite-assignment analysis for local variables, so the compiler checks that a variable is initialized before it is read.

You cannot simply write:

var message

without providing either a type or an initializer that allows the compiler to infer one.

Nullable and Non-Nullable Types in Kotlin

One of Kotlin's most important features is its null safety system.

In many programming languages, variables can unexpectedly contain null, which can cause runtime errors.

Kotlin distinguishes between nullable and non-nullable types.

Non-Nullable Variables

By default, a Kotlin variable declared as String cannot hold null.

fun main() {
    val name: String = "Rahul"

    println(name)
}

The following assignment is not allowed:

val name: String = null // Compilation error

Nullable Variables

To allow a variable to contain null, add a question mark (?) after its type.

fun main() {
    var name: String? = null

    name = "Rahul"

    println(name)
}

The type String? means the variable may contain either a string or null.

Safe Call Operator

When working with nullable values, you cannot directly access their members as though they were guaranteed to be non-null.

Use the safe call operator ?..

fun main() {
    val name: String? = null

    println(name?.length)
}

Output:

null

If name is null, the safe call returns null instead of attempting to access length.

Elvis Operator

The Elvis operator (?:) provides a fallback value when an expression is null.

fun main() {
    val name: String? = null

    val displayName = name ?: "Guest"

    println(displayName)
}

Output:

Guest

This is useful when you need a default value for nullable data.

Not-Null Assertion Operator

Kotlin also provides the not-null assertion operator (!!).

val name: String? = "Rahul"

println(name!!.length)

If name is non-null, the expression returns its length.

However, if name is null, the expression throws a NullPointerException.

Use !! carefully. Safe calls, null checks, and the Elvis operator are usually safer alternatives.

Type Conversion in Kotlin

Kotlin does not automatically convert every numeric type into another numeric type.

For example, an Int is not automatically converted into a Long simply because Long can represent a larger range of values.

Instead, Kotlin provides explicit conversion functions.

Converting Int to Long

fun main() {
    val number: Int = 100

    val longNumber: Long = number.toLong()

    println(longNumber)
}

Output:

100

Converting Double to Int

fun main() {
    val price: Double = 99.99

    val wholeNumber: Int = price.toInt()

    println(wholeNumber)
}

Output:

99

The fractional portion is discarded when converting this positive value to Int. This is not rounding.

Converting String to Int

You can convert a valid numeric string to an integer using toInt().

fun main() {
    val text = "123"

    val number = text.toInt()

    println(number)
}

Output:

123

However, invalid input causes a NumberFormatException.

val text = "hello"

val number = text.toInt() // Throws NumberFormatException

When the input may be invalid, use toIntOrNull().

fun main() {
    val text = "hello"

    val number = text.toIntOrNull()

    println(number)
}

Output:

null

This allows your program to handle invalid input without throwing an exception.

Type Checking and Smart Casts

Kotlin supports type checking with the is operator.

After certain type checks, the compiler can automatically treat a value as the more specific type. This is called a smart cast.

Example:

fun printLength(value: Any) {
    if (value is String) {
        println(value.length)
    }
}

fun main() {
    printLength("Kotlin")
    printLength(100)
}

Output:

6

When value is String evaluates to true, Kotlin knows that value is a string inside the corresponding branch.

You can therefore access value.length without manually casting it.

Smart casts are subject to certain conditions, particularly when the value could change between the type check and its use.

Constants in Kotlin

Sometimes you need a value that should remain constant throughout the application's execution.

Kotlin provides const val for compile-time constants.

Example:

const val APP_NAME = "CodeByte"

fun main() {
    println(APP_NAME)
}

The value of APP_NAME is known at compile time.

const val can be used only for properties declared at the top level or inside an object or companion object, and its type and initializer must satisfy Kotlin's compile-time constant requirements.

For example:

const val MAX_RETRIES = 3
const val API_VERSION = "v1"

By contrast, an ordinary val can be initialized using a value calculated at runtime.

val currentTime = System.currentTimeMillis()

This value is read-only after initialization, but it is not a compile-time constant.

Collections and Data Types in Kotlin

Kotlin also provides collection types for storing multiple values.

Three commonly used collection interfaces are List, Set, and Map.

List

A list stores elements in a defined order and may contain duplicate values.

fun main() {
    val names = listOf("Rahul", "Amit", "Priya")

    println(names)
    println(names[0])
}

Output:

[Rahul, Amit, Priya]
Rahul

listOf() creates a read-only list interface.

Set

A set represents a collection of distinct elements.

fun main() {
    val numbers = setOf(1, 2, 3, 2, 1)

    println(numbers)
}

The resulting set contains the distinct values 1, 2, and 3.

Map

A map stores key-value pairs.

fun main() {
    val user = mapOf(
        "name" to "Rahul",
        "city" to "Jaipur"
    )

    println(user["name"])
    println(user["city"])
}

Output:

Rahul
Jaipur

These collection types are useful for working with groups of related values.

Common Mistakes Beginners Make

Understanding common mistakes can help you write better Kotlin code.

1. Using var Everywhere

Although var is useful, unnecessary reassignment makes code harder to reason about.

Better approach: Prefer val when reassignment is not required.

2. Assuming Kotlin Automatically Converts Numeric Types

This does not work:

val number: Int = 100
val longNumber: Long = number // Compilation error

Use an explicit conversion:

val longNumber: Long = number.toLong()

3. Assigning Null to a Non-Nullable Variable

This is invalid:

val name: String = null

If a variable needs to hold null, declare it as nullable:

val name: String? = null

4. Using !! Without Checking for Null

The not-null assertion operator can cause a runtime exception.

Better approach: Use safe calls, null checks, or the Elvis operator whenever possible.

5. Forgetting the Float Suffix

This declaration infers a Double:

val temperature = 36.6

To create a Float, use:

val temperature = 36.6f

6. Using the Wrong Type for Large Numbers

An Int cannot represent every possible large integer.

Use Long when the expected value exceeds the Int range.

7. Using toInt() on Untrusted Input

Invalid numeric strings can cause exceptions.

Use toIntOrNull() when parsing input that may not be valid.

Best Practices for Kotlin Variables and Data Types

Follow these practices when writing Kotlin applications:

  1. Prefer val by default. Use var only when reassignment is necessary.

  2. Use meaningful variable names. Names such as totalPrice are clearer than x.

  3. Choose appropriate data types. Avoid using Any when a more specific type is available.

  4. Understand nullability. Use nullable types only when the absence of a value is meaningful.

  5. Avoid unnecessary !! assertions. Prefer safe calls and explicit null handling.

  6. Convert types explicitly. Kotlin's numeric conversion functions make conversions clear.

  7. Use type inference when it improves readability. You do not need to annotate every obvious type.

  8. Use const val for suitable compile-time constants. This communicates that the value is fixed at compile time.

  9. Handle invalid input safely. Functions such as toIntOrNull() are useful for parsing user input.

  10. Use collections appropriately. Choose lists, sets, or maps based on how the data should be represented.

Frequently Asked Questions

1. What are variables in Kotlin?

Variables are named references used to hold or access values in a program. Kotlin uses val for read-only references and var for reassignment.

2. What is the difference between val and var?

val prevents reassignment after initialization, while var allows reassignment. Both provide type safety.

3. Is Kotlin a statically typed language?

Yes. Kotlin is statically typed, meaning types are determined during compilation, either through explicit declarations or type inference.

4. What are the basic data types in Kotlin?

Common basic types include Int, Long, Short, Byte, Float, Double, Boolean, Char, and String.

5. What is type inference in Kotlin?

Type inference allows the Kotlin compiler to determine a variable's type from its initializer, reducing the need for explicit type annotations.

6. What is the difference between Int and Long?

Int is a signed 32-bit integer, while Long is a signed 64-bit integer. Long supports a much larger range of whole numbers.

7. How do you declare a nullable variable in Kotlin?

Add a question mark to the type.

val name: String? = null

This allows the variable to hold either a string or null.

8. How do you convert a String to an Int in Kotlin?

Use toInt() when the string is guaranteed to contain a valid integer. Use toIntOrNull() when the input may be invalid.

9. What is the difference between Float and Double?

Float uses 32-bit floating-point representation, while Double uses 64-bit representation and provides greater precision. Double is generally the default choice for decimal literals.

10. What is const val in Kotlin?

const val declares a compile-time constant. It is suitable for values that can be evaluated at compile time and meet Kotlin's restrictions for constant declarations.

11. Does Kotlin support type conversion automatically?

Kotlin supports type inference, but it does not automatically convert every numeric type into another. Explicit conversion functions such as toLong() and toInt() are used when needed.

12. Why is null safety important in Kotlin?

Null safety helps prevent many null-related errors by distinguishing nullable and non-nullable types at compile time.

Conclusion

Variables and data types are the foundation of every Kotlin application.

By understanding val, var, type inference, numeric types, strings, Boolean values, and null safety, you can write Kotlin programs that are easier to read and less prone to common errors.

Remember these key points:

  • Use val for references that should not be reassigned.

  • Use var when a variable needs to change.

  • Choose data types based on the values your application needs to represent.

  • Use type inference when the type is obvious.

  • Handle nullable values safely.

  • Convert between types explicitly when necessary.

  • Prefer specific types and meaningful variable names.

Whether you are learning Kotlin for Android development or backend programming, mastering these fundamentals will make it much easier to understand functions, classes, collections, and more advanced Kotlin features.

Start practicing with small programs, experiment with different types, and build your Kotlin skills one concept at a time.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘