0
0
Android Kotlinmobile~5 mins

Data types and type inference in Android Kotlin

Choose your learning style9 modes available
Introduction

Data types tell the app what kind of information it is working with. Type inference helps the app guess the data type automatically, so you write less code.

When you want to store a number like age or price.
When you need to keep text like a user's name or message.
When you want the app to figure out the type for you to save time.
When you want to avoid mistakes by clearly defining what kind of data you use.
When you want to work with true/false values to control app behavior.
Syntax
Android Kotlin
val variableName: DataType = value
val variableName = value // type inferred

val means the value cannot change (like a constant).

If you don't write the type, Kotlin guesses it from the value (type inference).

Examples
This creates a number variable called age with the value 25.
Android Kotlin
val age: Int = 25
Kotlin guesses name is a String because of the quotes.
Android Kotlin
val name = "Alice"
This stores a true/false value to check if something is active.
Android Kotlin
val isActive: Boolean = true
Kotlin infers price as a Double because of the decimal number.
Android Kotlin
val price = 19.99
Sample App

This program creates variables with different data types using both explicit types and type inference. It then prints each value.

Android Kotlin
fun main() {
  val userName = "Bob"
  val userAge: Int = 30
  val isMember = true
  val balance = 150.75

  println("Name: $userName")
  println("Age: $userAge")
  println("Member: $isMember")
  println("Balance: $balance")
}
OutputSuccess
Important Notes

Use val for values that don't change and var for values that can change.

Kotlin's type inference helps keep your code clean and easy to read.

Always choose the right data type to avoid errors and make your app faster.

Summary

Data types define what kind of data a variable holds.

Type inference lets Kotlin guess the data type from the value.

Use val for fixed values and var for variables that change.