Kotlin Basics — Variables, Data Types, and Syntax Guide
In this tutorial, you will learn about Kotlin Basics. We cover key concepts, practical examples, and best practices to help you master this topic.
Kotlin basics cover variables declared with val and var, primitive and reference data types, type inference, string templates, operators, and basic input-output operations that form the foundation of every Kotlin program.
What You'll Learn
- Declare variables with val (immutable) and var (mutable)
- Understand Kotlin's built-in data types: Int, Double, Boolean, Char, String
- Use type inference to reduce boilerplate
- Work with string templates for string interpolation
- Perform arithmetic and logical operations
- Read user input and print output
- Convert between types safely
Why It Matters
Every Kotlin program starts with variables and data types. Getting these fundamentals right prevents type-related errors, improves code readability, and sets the stage for more advanced concepts like null safety and collections. Kotlin's type system catches mistakes at compile time rather than runtime, saving hours of debugging. The skills you learn here apply directly to Android development, server-side programming, and all other Kotlin domains.
Real-World Use
DodaTech's Android configuration tool uses val for all configuration constants and var only for mutable state like user preferences. This discipline makes the codebase predictable and thread-safe. In production backend services, type inference keeps route handlers concise while maintaining full type safety.
Learning Path
flowchart LR A[Installation] --> B[Kotlin Basics\nYou are here] B --> C[Control Flow] style B fill:#f90,color:#fff
Variables: val versus var
Kotlin has two keywords for variable declaration.
- val: Immutable reference (read-only, like final in Java). Use by default.
- var: Mutable reference (can be reassigned). Use only when necessary.
fun main() {
val name = "Alice" // Immutable
var age = 25 // Mutable
val pi = 3.14159
// name = "Bob" // Error: Val cannot be reassigned
age = 26 // OK: Var can be reassigned
println("$name is $age years old")
println("Pi is approximately $pi")
}
Output: Alice is 26 years old followed by Pi is approximately 3.14159
The val keyword does not make the object itself immutable. It only prevents reassignment of the variable. A val list can still have elements added.
Type Inference
Kotlin infers types automatically. You do not need to specify the type explicitly most of the time.
fun main() {
val count = 42 // Inferred as Int
val price = 19.99 // Inferred as Double
val isReady = true // Inferred as Boolean
val letter = 'K' // Inferred as Char
val greeting = "Hello" // Inferred as String
println("$count, $price, $isReady, $letter, $greeting")
}
Output: 42, 19.99, true, K, Hello
You can specify the type explicitly when you want clarity or when the type cannot be inferred:
val exact: Int = 42
val text: String = "Explicit type"
Basic Data Types
| Type | Size | Example | Description |
|---|---|---|---|
| Byte | 8 bits | val b: Byte = 127 | Signed integer |
| Short | 16 bits | val s: Short = 32767 | Signed integer |
| Int | 32 bits | val i = 1000000 | Default integer type |
| Long | 64 bits | val l = 100L | Ends with L |
| Float | 32 bits | val f = 3.14F | Ends with F |
| Double | 64 bits | val d = 3.14159 | Default decimal type |
| Boolean | 1 bit | val b = true | true or false |
| Char | 16 bits | val c = 'A' | Single Unicode character |
| String | Variable | val s = "Hello" | Sequence of characters |
String Templates
Kotlin supports string interpolation directly in string literals.
fun main() {
val name = "Kotlin"
val year = 2026
val version = 2.0
// Simple variable reference
println("Language: $name")
// Expression in curly braces
println("Next year: ${year + 1}")
// Property access
println("Name length: ${name.length}")
// Complex expression
val price = 45.99
val quantity = 3
println("Total: ${price * quantity}")
}
Output:
Language: Kotlin
Next year: 2027
Name length: 6
Total: 137.97
String templates work inside both double-quoted strings and raw strings (triple-quoted).
Type Conversion
Kotlin does not automatically convert between numeric types. You must use conversion functions.
fun main() {
val intValue: Int = 100
val doubleValue: Double = intValue.toDouble()
val stringValue: String = intValue.toString()
val longValue: Long = intValue.toLong()
println(doubleValue) // Output: 100.0
println(stringValue) // Output: 100
println(longValue) // Output: 100
// Converting String to Int
val parsed = "42".toInt()
println(parsed + 8) // Output: 50
// Safe conversion returns null on failure
val failed = "abc".toIntOrNull()
println(failed) // Output: null
}
Output: Each conversion produces the expected result. The safe conversion toIntOrNull returns null instead of throwing an exception.
Basic Input
Read user input from the console using readln() (or readLine() in older versions).
fun main() {
print("Enter your name: ")
val name = readln()
print("Enter your age: ")
val age = readln().toInt()
println("Hello, $name! You are $age years old.")
println("Next year you will be ${age + 1}.")
}
Output: The program reads the user's name and age, then prints a personalized greeting.
Always use toIntOrNull() when reading numeric input to handle invalid input gracefully.
Operators
Kotlin supports standard arithmetic, comparison, and logical operators.
fun main() {
// Arithmetic
println("10 + 3 = ${10 + 3}") // 13
println("10 - 3 = ${10 - 3}") // 7
println("10 * 3 = ${10 * 3}") // 30
println("10 / 3 = ${10 / 3}") // 3 (integer division)
println("10.0 / 3 = ${10.0 / 3}") // 3.333...
println("10 % 3 = ${10 % 3}") // 1 (modulo)
// Comparison
val x = 5
val y = 10
println("x < y: ${x < y}") // true
println("x == y: ${x == y}") // false
// Logical
val a = true
val b = false
println("a && b: ${a && b}") // false
println("a || b: ${a || b}") // true
println("!a: ${!a}") // false
}
Output: All operators produce their expected results. Note that integer division truncates the decimal part.
Common Mistakes
Forgetting to convert input types: readln() returns a String. Using the value as a number without calling toInt() or toDouble() causes a type mismatch error.
Using var when val suffices: Overusing var makes code harder to reason about. Use val by default and change to var only when reassignment is needed.
Assuming automatic type conversion: Kotlin does not widen types automatically.
val x: Double = 10causes an error. Use 10.0 or10.toDouble().Mixing == and ===: In Kotlin, == calls equals() for structural comparison, and === checks referential identity. Java developers often confuse these.
Ignoring the difference between Int and Long: Large numbers may overflow Int silently. Use Long by appending L to the literal.
String concatenation versus templates: Using + for strings works but string templates with $ are more readable and efficient.
Practice Questions
- What is the difference between val and var?
Answer: val creates an immutable reference that cannot be reassigned once initialized. var creates a mutable reference that can be reassigned multiple times.
- How does Kotlin infer variable types?
Answer: Kotlin analyzes the initializer expression and assigns the appropriate type. For example, val x = 42 infers Int, val y = 3.14 infers Double.
- How do you safely convert a string to an integer without risking an exception?
Answer: Use toIntOrNull(). It returns the integer value if the string is a valid number, or null if Parsing fails.
- What is the output of
println("Result: ${10 / 3}")?
Answer: Result: 3. Integer division truncates the fractional part.
- Challenge: Write a Kotlin program that reads a temperature in Celsius from the user, converts it to Fahrenheit using the formula F = C * 9/5 + 32, and prints both values with proper type handling.
Answer:
fun main() {
print("Enter temperature in Celsius: ")
val input = readln()
val celsius = input.toDoubleOrNull()
if (celsius != null) {
val fahrenheit = celsius * 9.0 / 5.0 + 32
println("$celsius C = $fahrenheit F")
} else {
println("Invalid input. Please enter a number.")
}
}
Mini Project
Create a simple calculator that reads two numbers and an operator (+, -, *, /) from the user and prints the result. Requirements:
- Handle integer and decimal input
- Use toDoubleOrNull for safe conversion
- Support all four basic operations
- Print an error for division by zero
- Use string templates for clean output
This project reinforces type conversion, operators, conditionals, and basic I/O.
FAQ
What's Next
Now that you know Kotlin basics, learn control flow with if, when, and loops. You can also explore functions to organize your code into reusable blocks.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro