Kotlin supports two basic kinds of variable declarations, val and var. val is used to declare variables whose values will not change (similar to const variables in other languages), while var is used to declare variables whose values may change over time:
val PI : Double = 3.14159265 var x : Double = 3.5 PI = 22/7 // Illegal - PI is val x = 4.5 // OK - x is var
Kotlin offers automatic type deduction: when you declare a variable and initialize it at the same time Kotlin can deduce the type of the variable from the value you use to initialize it. This makes the type declaration part of the variable declaration optional.
val greeting = "Hello, " // greeting is String var name = "World" // name is String
Kotlin is a strongly typed language - once you have set the type for a variable you can not change it.
name = 42 // Illegal - name has type String
You can construct a String with embedded values by using String template expressions. A template expression in a String starts with a $.
val strOne = "Area is $(PI*x*x)" val circumference = 2.0*PI*x val strTwo = "Circumference is $circumference"
You can use + to concatenate strings.
val result = strOne + ". " + strTwo
Kotlin includes classes in their standard library for lists, sets, and dictionaries.
Kotlin lists come in two flavors, List and MutableList. The List type is fixed in size, while the MutableList can have items added to or removed from it.
To make a List or a MutableList from a fixed set of data items, use the appropriate constructor function:
val people = listOf("Alice","Betty","Charlie")
val fruits = mutableListOf("Apple","Banana","Cherry")
val person = people[1]
fruits.add("Grape")
fruits.removeAt(2)
You can make an empty list with the following syntax:
val animals = mutableListOf<String>()
animals.add("Aardvark")
animals.add("Badger")
animals.add("Cat")
A set is like a list, except it can not contain duplicates and it offers efficient search methods.
val setOfPeople = setOf("Alice","Betty","Charlie")
val isBobPresent = setOfPeople.contains("Bob")
Sets also come in mutable and immutable flavors.
Kotlin calls dictionaries maps:
val pets = mapOf("Alice" to "Dog","Betty" to "Cat","Charlie" to "Dog")
val charliesPet = pets["Charlie"]
Maps are immutable. If you want to be able to add new entries to the map or update existing entries you need to use a mutable map.
val cars = mutableMapOf("Alice" to "Camry","Betty" to "F150","Charlie" to "Tesla")
cars.put("David" to "Prius")
cars["Betty"] = "Tundra"