Variables, types and operators

Variables:

Assign-once (read-only) variables or constants:
Mutable variables:

Basic types:

Numbers:
Number types in Kotlin
TypeBit Witdth
Double64
Float32
Long64
Int32
Short16
Byte8
Tips:
  • Long numbers add an L to the end of the number à 328L
  • Hexadecimals: 0x0F
  • Binaries: 0b00001011
  • Octal literals are not supported.
  • Kotlin supports the conventional notation for float numbers:
  • Doubles: 325.3, 325.3e10.
  • Floats: 325.3f or 325.3F
  • You can use underscores to make numbers more readable: 2_000_000 (two million), 9876_5432_1012_3456L (credit card) …
  • The numbers will be stored as JVM primitive type, unless we need a nullable reference or generics. In these cases, numbers are boxed.
  • You can convert smaller numbers to bigger using the functions:
    • toByte(): Byte
    • toShort(): Short
    • toInt(): Int
    • toLong(): Long
    • toFloat(): Float
    • toDouble(): Double
    • toChar(): Char
Characters:

Represented by the type Char. There’s no difference between Java characters.

Booleans:

Represented by Boolean. There’s no difference between Java Booleans.

Arrays:

Represented by Array class. It has get and set functions and size property. To create an Array, you can use the function arrayOf() and pass the items as parameters like this:

blank

Arrays are invariant in Kotlin which means that we can’t assign, for example, Array to an Array. It prevents runtime failures.

Strings:

Represented by type String. The String can be iterated in a for loop, character by character:

blank

There are two types of string literals in Kotlin:

  • Escaped Strings: they have the same syntax than Java. They can contain escaped characters.
  • Raw Strings: They are delimited by a triple quote (“””). They don’t contain escaping characters and can contains more than one line.

blank

String Templates: Strings can contain template expression. A template expression starts with $. Here is an example:

blank

Operators:

Operators in Kotlin are the same as in Java. So, we will see only two new operators that Kotlin has added, the referential equality operators.

The referential equality operators are: === and !==. === is evaluated to true when the two variables point to the same object. It means, a === b will be evaluated to true if and only if a and b point to the same object.