Kotlin Tutorial menu

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:

KeywordMeaningCan change?
valvalue (read-only)No
varvariableYes

Example

kotlin
fun main() {
    val name = "Ayesha"   // cannot be changed
    var age = 19          // can be changed
    age = 20
    println("$name is $age years old")
}
Output
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

kotlin
fun main() {
    val price: Int = 250
    val quantity: Int = 4
    val total = price * quantity
    println("Total: Rs $total")
}
Output
Total: Rs 1000

Data Types

TypeStoresExample
IntWhole numbers42
LongVery large whole numbers3000000000L
DoubleDecimal numbers99.5
FloatDecimals with less precision4.5f
Booleantrue or falsetrue
CharOne character'A'
StringText"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

kotlin
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")
}
Output
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

kotlin
fun main() {
    var city: String? = null
    println(city?.length)
    println(city ?: "Unknown")

    city = "Karachi"
    println(city?.length)
}
Output
null
Unknown
7
  • ?. is the safe call. If the value is null, it returns null instead of crashing.
  • ?: is the Elvis operator. It gives a default value when the left side is null.
  • !! 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

kotlin
const val INSTITUTE = "Workownix"

fun main() {
    println("Welcome to $INSTITUTE")
}
Output
Welcome to Workownix

Exercise

Exercise

Which line creates a variable whose value can be changed later?

Learn Kotlin with a teacher

Join the App Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp