Kotlin Variables and Data Types
A variable is a named box that stores a value, such as a name, a price or a mark.
val and var
Kotlin has two keywords for creating variables:
| Keyword | Meaning | Can change? |
|---|---|---|
val | value (read-only) | No |
var | variable | Yes |
Example
fun main() {
val name = "Ayesha" // cannot be changed
var age = 19 // can be changed
age = 20
println("$name is $age years old")
}Ayesha is 20 years old
If you try name = "Sara", Kotlin shows an error, because name was made with val.
Use val by default. Switch to var only when the value really needs to change. This makes your code safer and easier to follow.
Type Inference
In the example above we never wrote a type. Kotlin looked at the value and inferred it: "Ayesha" is a String and 19 is an Int. You can also write the type yourself after a colon:
Example
fun main() {
val price: Int = 250
val quantity: Int = 4
val total = price * quantity
println("Total: Rs $total")
}Total: Rs 1000
Data Types
| Type | Stores | Example |
|---|---|---|
Int | Whole numbers | 42 |
Long | Very large whole numbers | 3000000000L |
Double | Decimal numbers | 99.5 |
Float | Decimals with less precision | 4.5f |
Boolean | true or false | true |
Char | One character | 'A' |
String | Text | "Karachi" |
A Char uses single quotes. A String uses double quotes.
Type Conversion
Kotlin does not change one type into another by itself. You convert with functions such as toInt(), toDouble() and toString():
Example
fun main() {
val text = "42"
val number = text.toInt()
println(number + 8)
val marks = 75
val percent = marks.toDouble() / 100
println(percent)
println(marks.toString() + " marks")
}50 0.75 75 marks
Null Safety
null means "no value". In many languages, using a null value by mistake crashes the program. Kotlin prevents this: a normal variable can never hold null.
To allow null, add a question mark after the type, like String?.
Example
fun main() {
var city: String? = null
println(city?.length)
println(city ?: "Unknown")
city = "Karachi"
println(city?.length)
}null Unknown 7
?.is the safe call. If the value isnull, it returnsnullinstead of crashing.?:is the Elvis operator. It gives a default value when the left side isnull.!!tells Kotlin "I am sure this is not null". If you are wrong, the program crashes, so use it rarely.
Constants
For values known before the program runs, use const val at the top of the file:
Example
const val INSTITUTE = "Workownix"
fun main() {
println("Welcome to $INSTITUTE")
}Welcome to Workownix
Exercise
Exercise
Which line creates a variable whose value can be changed later?
