Beginner: Kotlin · Kotlin basics · topic 2 of 50 · 30 min
First program, val and var, and types
Explanation
Your first program
fun main() {
println("Namaste, Kotlin!")
}fun is short for function, a named block of code. The curly braces hold its body. Unlike Java, you do not need a class or semicolons. Text in double quotes is a String.
val and var
A variable is a name for a value. Kotlin has two kinds. val (value) is read-only: once given a value, it cannot be reassigned. var (variable) can be reassigned. Professional Kotlin code uses val by default and var only when a value really changes, because values that never change make programs easier to understand.
fun main() {
val city = "Surat"
var visitors = 120
visitors = visitors + 30 // fine: var can change
// city = "Vadodara" // error: Val cannot be reassigned
println(city)
println(visitors) // 150
}Basic types
| Type | Holds | Example |
|---|---|---|
| Int | Whole numbers (about -2.1 billion to 2.1 billion) | val seats = 72 |
| Long | Bigger whole numbers | val population = 1_400_000_000L |
| Double | Decimal numbers | val price = 99.5 |
| Boolean | true or false | val isOpen = true |
| Char | One character in single quotes | val grade = 'A' |
| String | Text in double quotes | val name = "Ravi" |
Kotlin uses type inference: it works out the type from the value, so val seats = 72 is an Int. You can also write the type yourself after a colon: val seats: Int = 72. Once a variable has a type, it keeps it; you cannot later put text into an Int variable.
Numbers and division
fun main() {
println(7 / 2) // 3: Int divided by Int gives an Int (the decimal part is dropped)
println(7 % 2) // 1: the remainder
println(7 / 2.0) // 3.5: one Double makes the result a Double
println(7.toDouble() / 2) // 3.5
}String templates
A string template puts a value inside text. Write $name for a simple variable and ${ } around any expression. This is easier to read than joining text with +.
fun main() {
val item = "Masala dosa"
val price = 80
val qty = 3
println("$item x $qty = Rs ${price * qty}")
println("Name has ${item.length} characters")
}Converting text to numbers
fun main() {
val typed = "42"
val n = typed.toInt() // 42
val bad = "4two".toIntOrNull() // null: not a number
println(n + 1)
println(bad)
}Comments
A comment is a note for humans that the compiler ignores. // starts a one-line comment; /* ... */ wraps several lines. Use comments to explain why, not to repeat what the code obviously does.
Common mistakes
- Using var everywhere. Start with val; change to var only if the compiler says the value is reassigned.
- Expecting 7 / 2 to be 3.5. Integer division gives 3; use 7 / 2.0.
- Writing "Total: " + price + qty and getting "Total: 803" instead of 83. Use a template: "Total: ${price + qty}".
- Using toInt() on user input. One bad character crashes the app; use toIntOrNull().
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
First program, val and var, and types · 1/6
fun main() {
println("Namaste, Kotlin!")
}Every Kotlin program starts in fun main. println prints a line.
Prefer a video by a teacher? Find free videos on “kotlin basics val var types string templates tutorial” on YouTube ↗
In real life: A chai stall bill
A chai stall owner wants a quick calculation: cups sold and price per cup give the day's income. val is used for the fixed price, var for the running count that changes through the day, and a string template prints a clean summary.
fun main() {
val pricePerCup = 12
var cups = 0
cups += 85 // morning
cups += 120 // evening
println("Cups: $cups, income: Rs ${cups * pricePerCup}")
}Practice (0/3 done)
What does this print? fun main() { val a = 10 val b = 4 println("${a / b} ${a % b}") }
Which line does NOT compile?
In the Kotlin Playground, write a program for a phone recharge: a val for the plan price (299), a var for the wallet balance (500), subtract the price, and print "Balance after recharge: Rs X" with a string template. Then convert the text "149" to an Int and the text "abc" with toIntOrNull and print both.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Conditions: if and whenKotlin basics · same module
- Loops and rangesKotlin basics · same module
- Your first Dart program, variables and typesFlutter and Dart · Dart basics
- Interview questions: KotlinAndroid career path
- Types and variablesC# and .NET · Getting started with C# and .NET
- Classes and objectsClasses, objects and collections
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
Which keyword makes a read-only variable?
Answer: val
val values cannot be reassigned.
What is the type of val price = 49.99?
Answer: Double
Decimal literals are Double by default.
What does println(9 / 2) print?
Answer: 4
Int / Int is integer division.
What does "abc".toIntOrNull() return?
Answer: null
It returns null when the text is not a number.
How do you put an expression inside a string?
Answer: "Total: ${a + b}"
${ } evaluates the expression in a string template.
Which inserts an expression into a string?Related
Answer: 'Total: ${a + b}'
${...} evaluates the expression.
Which Kotlin feature replaces Java's switch statement?Related
Which Kotlin feature should you avoid because it can throw a NullPointerException?Related
What is wrong with: var x;Related
Answer: var needs a value on the same line so the compiler can infer the type
The compiler infers the type from the value, so var must be initialised.
From Types and variables
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 2 more topics in “Kotlin basics” before its exam: Conditions: if and when, Loops and ranges.
- Module 1 exam: Kotlin basics · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
- Then the next module, Null safety, functions and lambdas. 50 topics left in the course before the final exam.