Skip to content

Kotlin

Functions
Variables
  • Read-only variables with val
  • Mutable variables with var
  • Top Level Variables
    • Variables can be declared outside the main() function at the beginning of your program.
  • It is recommended to declare all variables as read-only by default. Use var only if necessary.
  • Variable Declaration with Type Specification
    • val age: Int or val currentProfit: Float
Literals : Numbers, Strings, Characters
  • The ability to infer type is called type inference
  • Kotlin Basic Types
    • Integers - Byte, Short, Int, Long
    • Unsigned Integers - UByte, UShort, UInt, ULong
    • Floating-point numbers - Float, Double
    • Boolean - Boolean
    • Characters - Char
    • Strings - String
Integer Numbers
  • An integer value with lots of digits can have underscores 1_000_000 for better reading
  • Even 1_2_3 is valid, but you cannot add _ and start or end of the number
  • Kotlin takes Double by default -- to accept float you have to write numbers as .2f etc.
Character
  • We wrap a symbol for character in single quote
Strings
  • Wrap characters in double quotes instead of single ones

  • String Templates

    • print the contents of variables to standard output
    • println("There are ${customers + 1} customers")
Comments
  • Three kinds of comments
  • End of line comments //
  • Multi Line comments /* */
  • Documentation Comments ``
Documentation Comments
  • Use these kinds of comments to automatically documentation about your source code using a special tool
  • These comments are placed above the declarations of respective program elements
  • /**
    *
    *
    *
    */
Collections
List
  • read-only list List \(\rightarrow\) listOf()
  • mutable list MutableList \(\rightarrow\) mutableListOf()
  • Explicit type specification for lists
    • val age: MutableList<Int> = MutableListOf(1,2,3)
  • To prevent unwanted modifications, you can create a read-only view of a mutable list by assigning it to a List. This is also called casting.
  • .first() & .last() method
Sets
  • Set \(\rightarrow\) setOf()
  • MutableSet \(\rightarrow\) mutableSetOf()
Maps
  • Map -> mapOf()
    • val readOnlyJuiceMenu = mapOf("apple" to 100, "kiwi" to 190, "orange" to 100)
    • using to keyword to map key to it's val
  • MutableMap -> mutableMapOf()