Kahibaro
Discord Login Register

3.1 Variables and Data Types

Why Variables Matter in Android Apps

Every Android app needs to remember things while it runs. It might need to remember a username, a score, or whether the user is logged in. In Kotlin, you use variables to store this changing information and data types to describe what kind of information it is.

Understanding variables and data types is essential before you can work with user input, layouts, and logic in Android. In this chapter you focus on how to declare, read, and update values in Kotlin, and how Kotlin’s type system keeps your code safe and predictable.

Immutable vs Mutable: `val` and `var`

Kotlin has two main ways to declare a variable. The keyword val creates a read-only reference. The keyword var creates a mutable reference.

Use val when the reference will not change after it is assigned. Use var when you need to reassign a new value.

For example:

val appName = "MyFirstApp"     // cannot be reassigned
var clickCount = 0             // can be reassigned later
clickCount = clickCount + 1    // ok
// appName = "NewName"        // error, val cannot be reassigned

val does not always mean that the underlying object is frozen. It means you cannot point the variable name to a different value. For example, a val list can often be modified through its functions, but you cannot assign a completely new list to that val.

In Android code you typically prefer val whenever possible. This makes your code easier to reason about, because you know which values never change.

In Kotlin:
val means the variable reference cannot be reassigned.
var means the variable reference can be reassigned.
Prefer val unless you truly need to change the reference.

Basic Numeric Types

Kotlin provides several numeric types. For most Android app logic you use Int, Long, Double, and Float. The others exist for special low level cases.

The main numeric types you will see are:

val age: Int = 25            // whole numbers, typical range
val population: Long = 8_000_000_000L
val price: Double = 19.99    // default type for decimals
val temperature: Float = 36.5F

The suffix L creates a Long. The suffix F creates a Float. Without a suffix, a whole number literal is an Int and a decimal literal is a Double.

Kotlin does not automatically convert between numeric types when that conversion might lose information. For example, you cannot assign an Int to a Long variable without conversion, even though a Long can hold larger numbers. You must convert explicitly.

You convert numeric types using conversion functions such as toInt(), toLong(), toDouble(), and toFloat():

val clicks: Int = 42
val clicksAsLong: Long = clicks.toLong()
val ratio: Double = 3.14
val ratioAsFloat: Float = ratio.toFloat()

This explicit conversion avoids silent data loss and unpredictable behavior.

Type Inference

Kotlin can usually guess the data type of a variable from the value you assign. This is called type inference. You do not have to write the type every time.

For example:

val score = 10          // inferred as Int
val pi = 3.14           // inferred as Double
val title = "Welcome"   // inferred as String

You can still write the type when you want to be explicit or when Kotlin cannot infer it:

val score: Int = 10
val pi: Double = 3.14

Type inference does not make Kotlin a dynamically typed language. Once a variable’s type is decided, it cannot change during execution. You cannot first store a number and later store a string in the same variable name.

Strings and Text

Strings are used constantly in Android apps for labels, messages, and user input. A String represents a sequence of characters. You create one with double quotes:

val greeting: String = "Hello, Android"
val userName = "Alex"

Kotlin supports string concatenation using the + operator:

val message = "Welcome, " + userName

String concatenation can become hard to read. Kotlin provides string templates for more readable code. You insert values directly into a string with $:

val age = 21
val info = "User: $userName, Age: $age"

If you need to use an expression rather than a simple variable, use ${}:

val score = 42
val result = "Final score: ${score * 2}"

In Android, you usually place user visible text in resource files, not directly in code. However, for quick debugging and simple internal messages, string literals in Kotlin code are common, so it is important to be comfortable with strings and string templates.

Characters and Booleans

A Char represents a single character, such as a letter or digit. You create it with single quotes:

val firstLetter: Char = 'A'
val digitChar: Char = '5'

A Boolean represents one of two values: true or false. Booleans are critical whenever you write conditions and control flow.

val isUserLoggedIn: Boolean = false
val hasNotifications = true

You will see booleans used in if statements and other control flow constructs, which are covered elsewhere. For now, understand that Boolean variables store truth values and that Kotlin does not allow you to use other types in their place. For example, you cannot use 1 instead of true.

Type Conversion and Safety

Kotlin’s type system is designed to catch incorrect usage at compile time. This often happens when you try to mix different types or expect a type to convert automatically.

For example, this does not compile:

val intValue: Int = 5
val doubleValue: Double = intValue    // error

You must convert explicitly:

val doubleValue: Double = intValue.toDouble()

This rule becomes important when you work with user input from EditText, because that input is always a String at first. To get a number from text, you must convert the String using functions like toInt() or toDouble(). You will see this pattern often in Android, and it can fail if the input does not contain a valid number.

Kotlin distinguishes clearly between text and numbers, and between different numeric sizes. This strong typing reduces bugs from unintended conversions, but it also means you must think carefully about which type you actually need for a particular value.

Top-level and Local Variables

In Kotlin you can declare variables inside functions or outside them. A variable declared inside a function is called a local variable. It can only be used within that function.

fun example() {
    val localMessage = "Hello"
    println(localMessage)
}
// println(localMessage)    // error, not visible here

You can also declare variables at the top of a Kotlin file, outside any class or function. These are top level variables. In Android, top level val constants are sometimes used for things like keys, tags, or configuration values.

To mark a value as a compile time constant, you can use const val. This is often used with strings for configuration keys or for logging tags.

const val LOG_TAG = "MainActivity"

Unlike regular val, a const val must be a simple value known at compile time, such as a literal number or string. It cannot be calculated at runtime.

Choosing the Right Type

When you declare a variable, you are making a small design decision about your data. In Android you frequently decide between numeric and text types, and between mutable and immutable references.

Some practical guidelines are:

Use Int for counts, indexes, and most whole numbers in app logic.

Use Double for general decimal values where precision is not extremely critical, such as basic measurements.

Use String for anything that is human readable text, even if it represents a number like a phone number or an ID that you will not calculate with.

Use Boolean for states that have only two possibilities, such as enabled or disabled.

Use val by default and only use var when you know the reference must change.

These decisions affect how safely and clearly you can express your app’s behavior. Kotlin’s type system guides you toward clearer code, especially when you interact with Android UI elements and system APIs.

Always think about two things when you declare a variable:

  1. Should it be val or var?
  2. What is the most specific and correct type for this value?
    Clear answers to these questions lead to fewer bugs and more readable Android code.

Views: 2

Comments

Please login to add a comment.

Don't have an account? Register now!