Basics
Literals
Integer numbers
Characters
Strings
Variables
val
(for value) declares an immutable variable (just a named value or a constant), which cannot be changed after it has been initialized (this is actually not entirely true).
It is always possible to change the internal state of a val
variable: while it is prohibited to reassign the variable, its content can be modified in some other ways.
// list creation
val myMutableList = mutableListOf(1, 2, 3, 4, 5)
// trying to update the list
myMutableList = mutableListOf(1, 2, 3, 4, 5, 6) // error line
// adding a new element
myMutableList.add(6) // it works
// printing the list
println(myMutableList) // [1, 2, 3, 4, 5, 6]
var
(for variable) declares a mutable variable, which can be changed (as many times as needed).
const
modifier is used before theval
keyword to declare a compile-time constant.
const val CONST_INT = 127
const val CONST_DOUBLE = 3.14
const val CONST_CHAR = 'c'
const val CONST_STRING = "I am constant"
const val CONST_ARRAY = arrayOf(1, 2, 3)
// error: only primitives and strings are allowed
fun main() {
const val MY_INT_2 = 2048
// error: Modifier 'const' is not applicable to 'local variable'
}
Data types
Kotlin determines the data types of variables automatically. This mechanism is called type inference.
The type of a variable can also be specified when declaring it:
val/var identifier: Type = initialization
Functions
All functions return a result, even the println
function.
val result = println("text")
println(result) // kotlin.Unit
The result is a special value called Unit
, which practically means no result
. When your function returns nothing, it means it returns Unit
, you can think of it as Void
.
Last updated
Was this helpful?