DEV Community

Gurkirat Singh
Gurkirat Singh

Posted on • Edited on

Pocket Guide on Kotlin

Preface

This is a practical guide on kotlin language. This one file can be used as your pocket reference if you had already mastered the language or a life savior for the newbies who are looking for a short and simple tutorial.

I will try to update it frequently, but you can feel free to add examples in codes/ directory or commit changes in readme file

NOTE: This is exported from jupyter notebook. If you want that, mail me tbhaxor@gmail.com

Introduction

Kotlin is a cross-platform, statically typed, general-purpose programming language with type inference

Every kotlin program starts from the main function, as demonstrated below

fun main(args: Array<String>) {
        // your code
}
Enter fullscreen mode Exit fullscreen mode

NOTE : Since this is an interactive notebook, the main function part will be skipped.

Basics

Printing on the console

Documentation: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/println.html#println

println("Hello World")
Enter fullscreen mode Exit fullscreen mode
Hello World
Enter fullscreen mode Exit fullscreen mode

Variables

Variables are used to store the value of specific type, the types supported by kotlin there in documentation

Documentation: https://kotlinlang.org/docs/reference/basic-types.html, https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/

var age: Int = 22
age
Enter fullscreen mode Exit fullscreen mode
22
Enter fullscreen mode Exit fullscreen mode

Changing value of the variable

age = 30
age
Enter fullscreen mode Exit fullscreen mode
30
Enter fullscreen mode Exit fullscreen mode

Kotlin support three types of variables

  • var → mutable variables, values of such variables can be changed during the program set
  • val → immutable variables, values of such variables can be initialized only single time
val i = 10
i
Enter fullscreen mode Exit fullscreen mode
10
Enter fullscreen mode Exit fullscreen mode
i = 20
Enter fullscreen mode Exit fullscreen mode
Val cannot be reassigned
Enter fullscreen mode Exit fullscreen mode
i
Enter fullscreen mode Exit fullscreen mode
10
Enter fullscreen mode Exit fullscreen mode

Using underscored number literal

val oneMillion = 1_000_000
oneMillion
Enter fullscreen mode Exit fullscreen mode
1000000
Enter fullscreen mode Exit fullscreen mode

Floating Numbers

Documentation: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-float/

// the f means to use floating number, otherwise it will use the double and then type cast it into float
val price: Float = 44.77f;
price
Enter fullscreen mode Exit fullscreen mode
44.77
Enter fullscreen mode Exit fullscreen mode

Strings

Documentation: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/

var name: String = "Gurkirat Singh"
name
Enter fullscreen mode Exit fullscreen mode
Gurkirat Singh
Enter fullscreen mode Exit fullscreen mode

Length of string

name.length
Enter fullscreen mode Exit fullscreen mode
14
Enter fullscreen mode Exit fullscreen mode

Getting one character

name[0] == name.get(0)
Enter fullscreen mode Exit fullscreen mode
true
Enter fullscreen mode Exit fullscreen mode

Comparing two strings

val name2 = "Gurkirat Singh"
name2
Enter fullscreen mode Exit fullscreen mode
Gurkirat Singh
Enter fullscreen mode Exit fullscreen mode
name == name2
Enter fullscreen mode Exit fullscreen mode
true
Enter fullscreen mode Exit fullscreen mode
name.compareTo(name2)
Enter fullscreen mode Exit fullscreen mode
0
Enter fullscreen mode Exit fullscreen mode

Here 0 means both strings are identical

Concatenating two strings

name.plus(name2)
Enter fullscreen mode Exit fullscreen mode
Gurkirat SinghGurkirat Singh
Enter fullscreen mode Exit fullscreen mode
name + name2
Enter fullscreen mode Exit fullscreen mode
Gurkirat SinghGurkirat Singh
Enter fullscreen mode Exit fullscreen mode

Arrays

Collection of similar type of data

Documentation: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-array/

var numbers = arrayOf(1, 2, 3, 4, 5, 6)
numbers
Enter fullscreen mode Exit fullscreen mode
[Ljava.lang.Integer;@728561a2
Enter fullscreen mode Exit fullscreen mode

To get the value, use the index number

numbers[0]
Enter fullscreen mode Exit fullscreen mode
1
Enter fullscreen mode Exit fullscreen mode
numbers[4]
Enter fullscreen mode Exit fullscreen mode
5
Enter fullscreen mode Exit fullscreen mode

Getting the length of array

numbers.size
Enter fullscreen mode Exit fullscreen mode
6
Enter fullscreen mode Exit fullscreen mode

Empty array of specific type

val emptyArray = arrayOf<Int>()
emptyArray
Enter fullscreen mode Exit fullscreen mode
[Ljava.lang.Integer;@303524fb
Enter fullscreen mode Exit fullscreen mode
emptyArray.size
Enter fullscreen mode Exit fullscreen mode
0
Enter fullscreen mode Exit fullscreen mode

Type Conversion

val num1 = 1
val num2 = "2"
Enter fullscreen mode Exit fullscreen mode

Both look identical (numbers), but the type of both the variables are not same

num1 + num2
Enter fullscreen mode Exit fullscreen mode
None of the following functions can be called with the arguments supplied: 
public final operator fun plus(other: Byte): Int defined in kotlin.Int
public final operator fun plus(other: Double): Double defined in kotlin.Int
public final operator fun plus(other: Float): Float defined in kotlin.Int
public final operator fun plus(other: Int): Int defined in kotlin.Int
public final operator fun plus(other: Long): Long defined in kotlin.Int
public final operator fun plus(other: Short): Int defined in kotlin.Int
Enter fullscreen mode Exit fullscreen mode
num1 + num2.toInt()
Enter fullscreen mode Exit fullscreen mode
3
Enter fullscreen mode Exit fullscreen mode

Operators and Operands

Documentation: https://kotlinlang.org/docs/reference/keyword-reference.html#operators-and-special-symbols

Arithmatic Operators

val num1 = 20
val num2 = 30
Enter fullscreen mode Exit fullscreen mode

Addition

num1 + num2
Enter fullscreen mode Exit fullscreen mode
50
Enter fullscreen mode Exit fullscreen mode

Subtraction

num2 - num1
Enter fullscreen mode Exit fullscreen mode
10
Enter fullscreen mode Exit fullscreen mode

Multiplication

num1 * num2
Enter fullscreen mode Exit fullscreen mode
600
Enter fullscreen mode Exit fullscreen mode

Division

num2 / num1
Enter fullscreen mode Exit fullscreen mode
1
Enter fullscreen mode Exit fullscreen mode
num2.toFloat() / num1.toFloat()
Enter fullscreen mode Exit fullscreen mode
1.5
Enter fullscreen mode Exit fullscreen mode

Finding remainder

num2 % num1
Enter fullscreen mode Exit fullscreen mode
10
Enter fullscreen mode Exit fullscreen mode

Relation Operators

val num1 = 20
val num2 = 30
Enter fullscreen mode Exit fullscreen mode

Equality

num1 == num2
Enter fullscreen mode Exit fullscreen mode
false
Enter fullscreen mode Exit fullscreen mode

NOTE: Don't misunderstand == with =. First one is called equal to operator and another is called assignment operator (evaluates and assigns the RHS value to LHS)

Less than

num1 < num2
Enter fullscreen mode Exit fullscreen mode
true
Enter fullscreen mode Exit fullscreen mode
num2 < num2
Enter fullscreen mode Exit fullscreen mode
false
Enter fullscreen mode Exit fullscreen mode

Greater than

num1 > num2
Enter fullscreen mode Exit fullscreen mode
false
Enter fullscreen mode Exit fullscreen mode

Greater than equal to

num1 >= num1
Enter fullscreen mode Exit fullscreen mode
true
Enter fullscreen mode Exit fullscreen mode

Less than equal to

num1 <= num1
Enter fullscreen mode Exit fullscreen mode
true
Enter fullscreen mode Exit fullscreen mode

Not equal to

num1 != num2
Enter fullscreen mode Exit fullscreen mode
true
Enter fullscreen mode Exit fullscreen mode

Unary Operators

var num1 = 10
num1
Enter fullscreen mode Exit fullscreen mode
10
Enter fullscreen mode Exit fullscreen mode

Post increment

num1++
num1
Enter fullscreen mode Exit fullscreen mode
11
Enter fullscreen mode Exit fullscreen mode

Pre increment

++num1
num1
Enter fullscreen mode Exit fullscreen mode
12
Enter fullscreen mode Exit fullscreen mode

Post decrement

num1--
num1
Enter fullscreen mode Exit fullscreen mode
11
Enter fullscreen mode Exit fullscreen mode

Pre decrement

--num1
num1
Enter fullscreen mode Exit fullscreen mode
10
Enter fullscreen mode Exit fullscreen mode

Bitwise Operator

var num1 = 10
var num2 = 20
Enter fullscreen mode Exit fullscreen mode
num1.toString(2)
Enter fullscreen mode Exit fullscreen mode
1010
Enter fullscreen mode Exit fullscreen mode
num2.toString(2)
Enter fullscreen mode Exit fullscreen mode
10100
Enter fullscreen mode Exit fullscreen mode

Shift left by one bit

num1 = num1.shl(1)
num1.toString(2)
Enter fullscreen mode Exit fullscreen mode
10100
Enter fullscreen mode Exit fullscreen mode

Shift right by one bit

num1 = num1.shr(1)
num1.toString(2)
Enter fullscreen mode Exit fullscreen mode
1010
Enter fullscreen mode Exit fullscreen mode

Bitwise or

num1.or(num2).toString(2)
Enter fullscreen mode Exit fullscreen mode
11110
Enter fullscreen mode Exit fullscreen mode

Bitwise and

num1.and(num2).toString(2)
Enter fullscreen mode Exit fullscreen mode
0
Enter fullscreen mode Exit fullscreen mode

Bitwise xor

num1.xor(num2).toString(2)
Enter fullscreen mode Exit fullscreen mode
11110
Enter fullscreen mode Exit fullscreen mode
num1.and(num1).toString(2)
Enter fullscreen mode Exit fullscreen mode
1010
Enter fullscreen mode Exit fullscreen mode

Bitwise inverse

num1.inv().toString(2)
Enter fullscreen mode Exit fullscreen mode
-1011
Enter fullscreen mode Exit fullscreen mode
num1.inv()
Enter fullscreen mode Exit fullscreen mode
-11
Enter fullscreen mode Exit fullscreen mode

Logical Operators

AND operator

true && true
Enter fullscreen mode Exit fullscreen mode
true
Enter fullscreen mode Exit fullscreen mode
false && true
Enter fullscreen mode Exit fullscreen mode
false
Enter fullscreen mode Exit fullscreen mode
true && false
Enter fullscreen mode Exit fullscreen mode
false
Enter fullscreen mode Exit fullscreen mode
false && false
Enter fullscreen mode Exit fullscreen mode
false
Enter fullscreen mode Exit fullscreen mode

OR operator

true || true
Enter fullscreen mode Exit fullscreen mode
true
Enter fullscreen mode Exit fullscreen mode
true || false
Enter fullscreen mode Exit fullscreen mode
true
Enter fullscreen mode Exit fullscreen mode
false || true
Enter fullscreen mode Exit fullscreen mode
true
Enter fullscreen mode Exit fullscreen mode
false || false
Enter fullscreen mode Exit fullscreen mode
false
Enter fullscreen mode Exit fullscreen mode

NOT Operator

true && !false
Enter fullscreen mode Exit fullscreen mode
true
Enter fullscreen mode Exit fullscreen mode

Conditionals

IF - ELSE

Documentation: https://kotlinlang.org/docs/reference/control-flow.html#if-expression

var age = 18
var age2 = 14
Enter fullscreen mode Exit fullscreen mode
if (age >= 18) {
    println("You are an adult")
}
else {
    println("Hey kiddo")
}
Enter fullscreen mode Exit fullscreen mode
You are an adult
Enter fullscreen mode Exit fullscreen mode
if (age2 >= 18) {
    println("You are an adult")
}
else {
    println("Hey kiddo")
}
Enter fullscreen mode Exit fullscreen mode
Hey kiddo
Enter fullscreen mode Exit fullscreen mode

WHEN

Documentation: https://kotlinlang.org/docs/reference/control-flow.html#when-expression

var num = 4
Enter fullscreen mode Exit fullscreen mode
when(num) {
    1 -> println("Sunday")
    2 -> println("Monday")
    3 -> println("Tuesday")
    4 -> println("Wednesday")
    5 -> println("Thursday")
    6 -> println("Friday")
    7 -> println("Saturday")
    else -> println("Number should be in between 1 and 7") // will be executed if no value matches
}
Enter fullscreen mode Exit fullscreen mode
Wednesday
Enter fullscreen mode Exit fullscreen mode

To run same lines of code for multiple choices

when(variable) {
    1, 2, 3 -> println("your input is either 1 or 2 or 3")
    else -> {
        // running multiple lines
        println("This is not a joke")
        println("Enter number 1, 2, 3 only")
    }
}
Enter fullscreen mode Exit fullscreen mode

To run same lines of code for a range of numbers

when(variable) {
    in 1..3 -> println("your input is either 1 or 2 or 3")
    else -> {
        // running multiple lines
        println("This is not a joke")
        println("Enter number 1, 2, 3 only")
    }
}
Enter fullscreen mode Exit fullscreen mode

FOR Loop

Documentation: https://kotlinlang.org/docs/reference/control-flow.html#for-loops

var numbers = arrayOf<Int>(1, 2, 3, 4, 5, 6)
Enter fullscreen mode Exit fullscreen mode

Simple demonstration

for (number in numbers){
    println(number)
}
Enter fullscreen mode Exit fullscreen mode
1
2
3
4
5
6
Enter fullscreen mode Exit fullscreen mode

With indices

for ((idx, number) in numbers.withIndex()) {
    println("number '$number' is at index '$idx' in the array")
}
Enter fullscreen mode Exit fullscreen mode
number '1' is at index '0' in the array
number '2' is at index '1' in the array
number '3' is at index '2' in the array
number '4' is at index '3' in the array
number '5' is at index '4' in the array
number '6' is at index '5' in the array
Enter fullscreen mode Exit fullscreen mode

Range based loop

for (i in 1..5)
{
    println(i)
}
Enter fullscreen mode Exit fullscreen mode
1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

Range based loop with step

for (i in 1..5 step 2)
{
    println(i)
}
Enter fullscreen mode Exit fullscreen mode
1
3
5
Enter fullscreen mode Exit fullscreen mode

Reverse loop with step

for (i in 6 downTo 0 step 2)
{
    println(i)
}
Enter fullscreen mode Exit fullscreen mode
6
4
2
0
Enter fullscreen mode Exit fullscreen mode

WHILE and DO-WHILE Loop

Documentation: https://kotlinlang.org/docs/reference/control-flow.html#while-loops

var num = 5
Enter fullscreen mode Exit fullscreen mode

While Loop

while (num > 0)
{
    println(num--)
}
Enter fullscreen mode Exit fullscreen mode
5
4
3
2
1
Enter fullscreen mode Exit fullscreen mode

Do While Loop

do {
    println(num--)
} while (num > 0)
Enter fullscreen mode Exit fullscreen mode
0
Enter fullscreen mode Exit fullscreen mode

Difference between while and do-while loop: https://stackoverflow.com/a/3347010/10362396

Jump statements like break and continue are used to end and skip the following loop body.

Documentation: https://kotlinlang.org/docs/reference/returns.html#returns-and-jumps

Functions

A function is a unit of code that performs a special task. In programming, function is used to break the code into smaller modules which makes the program more manageable.

Declaring a function

Documentation: https://kotlinlang.org/docs/reference/functions.html#function-declarations

Simple function

fun greet() {
    println("Hello User")
}
Enter fullscreen mode Exit fullscreen mode
greet()
Enter fullscreen mode Exit fullscreen mode
Hello User
Enter fullscreen mode Exit fullscreen mode

Receiving parameters

fun sum(x: Int, y: Int) {
    println(x+y)
}
Enter fullscreen mode Exit fullscreen mode
sum(10, 11)
Enter fullscreen mode Exit fullscreen mode
21
Enter fullscreen mode Exit fullscreen mode

Calling function with wrong type

sum(10.4f, 11)
Enter fullscreen mode Exit fullscreen mode
The floating-point literal does not conform to the expected type Int
Enter fullscreen mode Exit fullscreen mode

Return statements

fun say_hello(name: String) : String {
    return "Hello, " + name
}
Enter fullscreen mode Exit fullscreen mode
say_hello("John")
Enter fullscreen mode Exit fullscreen mode
Hello, John
Enter fullscreen mode Exit fullscreen mode
say_hello("Dale")
Enter fullscreen mode Exit fullscreen mode
Hello, Dale
Enter fullscreen mode Exit fullscreen mode

Recursion

A function which calls itself is called as recursive function and this process of repetition is called recursion.

fun factorial(num: Int): Int {
    // base condition
    if (num <= 1) {
        return 1
    }

    // function calling itself
    return num * factorial(num - 1)
}
Enter fullscreen mode Exit fullscreen mode
factorial(5)
Enter fullscreen mode Exit fullscreen mode
120
Enter fullscreen mode Exit fullscreen mode

Default arguments

Documentation: https://kotlinlang.org/docs/reference/functions.html#default-arguments

fun say_hello_default(name: String = "Guest"): String {
    return "Hello, " + name
}
Enter fullscreen mode Exit fullscreen mode
say_hello_default()
Enter fullscreen mode Exit fullscreen mode
Hello, Guest
Enter fullscreen mode Exit fullscreen mode
say_hello_default("Sheldon")
Enter fullscreen mode Exit fullscreen mode
Hello, Sheldon
Enter fullscreen mode Exit fullscreen mode

Named arguments

Documentation: https://kotlinlang.org/docs/reference/functions.html#named-arguments

fun say_hello_default_name(name: String = "Guest", robot: String): String {
    return "Hello, " + name + ". I am " + robot
}
Enter fullscreen mode Exit fullscreen mode
say_hello_default_name(robot = "Alex")
Enter fullscreen mode Exit fullscreen mode
Hello, Guest. I am Alex
Enter fullscreen mode Exit fullscreen mode
say_hello_default_name("Dale", robot = "Alice")
Enter fullscreen mode Exit fullscreen mode
Hello, Dale. I am Alice
Enter fullscreen mode Exit fullscreen mode

Lambda Functions

The lambda functions are the functions that are not declared, but passed immediately as an expression

Documentation: https://kotlinlang.org/docs/reference/lambdas.html#lambda-expressions-and-anonymous-functions

fun multiply(x: Int, y: Int, callback: (Int) -> Unit)
{
    callback(x * y)
}
Enter fullscreen mode Exit fullscreen mode
var cb: (Int) -> Unit = {p -> println("The product is $p") } // lambda function
multiply(10, 20, cb)
Enter fullscreen mode Exit fullscreen mode
The product is 200
Enter fullscreen mode Exit fullscreen mode

Higher order functions

Function that accept functions as the parameters and can return function as a value. This is basically implemented by the lambda functions

Documentation: https://kotlinlang.org/docs/reference/lambdas.html#higher-order-functions

Accepting function

var fn:(Int, Int) -> Int = {x, y-> x + y};

fun adder(num1: Int, num2: Int, callback: (Int, Int) -> Int): Int {
    return callback(num1, num2)
}
Enter fullscreen mode Exit fullscreen mode
adder(10, 20, fn)
Enter fullscreen mode Exit fullscreen mode
30
Enter fullscreen mode Exit fullscreen mode

Inline function

Documentation: https://kotlinlang.org/docs/reference/inline-functions.html

inline fun inlineFunc(myFunc: () -> Unit): Unit {
    myFunc()
}
Enter fullscreen mode Exit fullscreen mode
inlineFunc({println("Printing inside inline function")})
Enter fullscreen mode Exit fullscreen mode
Printing inside inline function
Enter fullscreen mode Exit fullscreen mode

Exception Handling

Try Catch

Documentation: https://kotlinlang.org/docs/tutorials/kotlin-for-py/exceptions.html#throwing-and-catching

var num1 = 100
var num2 = 0
Enter fullscreen mode Exit fullscreen mode
try {
    num1 / num2
} catch (e: ArithmeticException) {
    println("Attempeted divide by zero")
}
Enter fullscreen mode Exit fullscreen mode
Attempeted divide by zero
Enter fullscreen mode Exit fullscreen mode

Try-Catch as an Expression

fun toInt(v: String): Int {
    return try {
        Integer.parseInt(v)
    } catch (e: NumberFormatException) {
        0
    }
}
Enter fullscreen mode Exit fullscreen mode
toInt("10")
Enter fullscreen mode Exit fullscreen mode
10
Enter fullscreen mode Exit fullscreen mode
toInt("hello")
Enter fullscreen mode Exit fullscreen mode
0
Enter fullscreen mode Exit fullscreen mode

The finally blocks runs regardless of the successful or failed execution

try {
    // some code
} catch (e: Exception) {
    //some execption
} finally {
    // this will run after try or catch block execution
}
Enter fullscreen mode Exit fullscreen mode

Throwing Exception

fun divMe(x: Int, y: Int): Int {
    if (y < 0){
        throw IllegalArgumentException("y should be strictly greater than 0")
    }

    return x / y
}
Enter fullscreen mode Exit fullscreen mode
try {
    divMe(10, 0)
} catch (e: ArithmeticException) {
    print("Aborted: ")
    println(e)
} catch (e: IllegalArgumentException) {
    print("Aborted: ")
    println(e)
}
Enter fullscreen mode Exit fullscreen mode
Aborted: java.lang.ArithmeticException: / by zero
Enter fullscreen mode Exit fullscreen mode
try {
    divMe(10, -20)
} catch (e: ArithmeticException) {
    print("Aborted: ")
    println(e)
} catch (e: IllegalArgumentException) {
    print("Aborted: ")
    println(e)
}
Enter fullscreen mode Exit fullscreen mode
Aborted: java.lang.IllegalArgumentException: y should be strictly greater than 0
Enter fullscreen mode Exit fullscreen mode

NULL Safety

Documentation: https://kotlinlang.org/docs/reference/null-safety.html#nullable-types-and-non-null-types

var myVar: Int = 7
myVar
Enter fullscreen mode Exit fullscreen mode
7
Enter fullscreen mode Exit fullscreen mode
myVar = 10
myVar
Enter fullscreen mode Exit fullscreen mode
10
Enter fullscreen mode Exit fullscreen mode
myVar = null
Enter fullscreen mode Exit fullscreen mode
Null can not be a value of a non-null type Int
Enter fullscreen mode Exit fullscreen mode

Use Int? while defining the variable, so as to accept null values

var myVar: Int? = 7
myVar
Enter fullscreen mode Exit fullscreen mode
7
Enter fullscreen mode Exit fullscreen mode
myVar = 10
myVar
Enter fullscreen mode Exit fullscreen mode
10
Enter fullscreen mode Exit fullscreen mode
myVar = null
myVar
Enter fullscreen mode Exit fullscreen mode

Safe Casting

Documentation: https://kotlinlang.org/docs/reference/null-safety.html#safe-casts

var num: Int? = 19
num = null
Enter fullscreen mode Exit fullscreen mode
var num2: Int? = num as? Int
num2
Enter fullscreen mode Exit fullscreen mode
num = 10
Enter fullscreen mode Exit fullscreen mode
var num2: Int? = num as? Int
num2
Enter fullscreen mode Exit fullscreen mode
10
Enter fullscreen mode Exit fullscreen mode

Elvis Operator

Documentation: https://kotlinlang.org/docs/reference/null-safety.html#elvis-operator

val s1: String? = null;
val s2: String? = "Hello World";
Enter fullscreen mode Exit fullscreen mode
var l1: Int = if (s1 != null) s1.length else -1
l1
Enter fullscreen mode Exit fullscreen mode
-1
Enter fullscreen mode Exit fullscreen mode
var l2: Int = if (s2 != null) s2.length else -1
l2
Enter fullscreen mode Exit fullscreen mode
11
Enter fullscreen mode Exit fullscreen mode

Simplifying the above with elvis operator

var l1: Int = s1 ?.length ?: -1
l1
Enter fullscreen mode Exit fullscreen mode
-1
Enter fullscreen mode Exit fullscreen mode
var l2: Int = s2 ?.length ?: -1
l2
Enter fullscreen mode Exit fullscreen mode
11
Enter fullscreen mode Exit fullscreen mode

Collections

Lists

Documentation:https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/

Immutable List: listOf

Documentation: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/list-of.html

var numbers = listOf(1, 2, "3", 4, 5)

for (number: Any in numbers) {
    println(number)
}
Enter fullscreen mode Exit fullscreen mode
1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

List with type specification

var numbers = listOf<Int>(1, 2, 3, 4, 5)

for (number: Int in numbers) {
    println(number)
}
Enter fullscreen mode Exit fullscreen mode
1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

Mutable List: mutableListOf

Documentation: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/mutable-list-of.html

var list = mutableListOf<Int>()
Enter fullscreen mode Exit fullscreen mode
list.isEmpty()
Enter fullscreen mode Exit fullscreen mode
true
Enter fullscreen mode Exit fullscreen mode
list.size
Enter fullscreen mode Exit fullscreen mode
0
Enter fullscreen mode Exit fullscreen mode

Adding an element

list.add(10)
list.size
Enter fullscreen mode Exit fullscreen mode
1
Enter fullscreen mode Exit fullscreen mode
list[0]
Enter fullscreen mode Exit fullscreen mode
10
Enter fullscreen mode Exit fullscreen mode

Adding multiple elements

list.addAll(listOf(20, 30, 40))
list.size
Enter fullscreen mode Exit fullscreen mode
4
Enter fullscreen mode Exit fullscreen mode

Arrays: arrayListOf

Documentation: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/array-list-of.html

var array = arrayListOf<Int>(10, 20, 30)
for(element in array) {
    println(element)
}
Enter fullscreen mode Exit fullscreen mode
10
20
30
Enter fullscreen mode Exit fullscreen mode
array.add(100)
for(element in array) {
    println(element)
}
Enter fullscreen mode Exit fullscreen mode
10
20
30
100
Enter fullscreen mode Exit fullscreen mode
array[2] = -100
for(element in array) {
    println(element)
}
Enter fullscreen mode Exit fullscreen mode
10
20
-100
100
Enter fullscreen mode Exit fullscreen mode

Inserting at specific location

array.add(1, -200)
for(element in array) {
    println(element)
}
Enter fullscreen mode Exit fullscreen mode
10
-200
20
-100
100
Enter fullscreen mode Exit fullscreen mode

Map

Documentation: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-map/

Immutable Map: mapOf

Documentation: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/map-of.html

var map: Map<String, Int> = mapOf<String, Int>("ONE" to 1, "TWO" to 2)
Enter fullscreen mode Exit fullscreen mode
map["ONE"]
Enter fullscreen mode Exit fullscreen mode
1
Enter fullscreen mode Exit fullscreen mode
map.keys
Enter fullscreen mode Exit fullscreen mode
[ONE, TWO]
Enter fullscreen mode Exit fullscreen mode
for (key in map.keys) {
    println(map[key])
}
Enter fullscreen mode Exit fullscreen mode
1
2
Enter fullscreen mode Exit fullscreen mode

Mutable Map: mutableMapOf

Documentation: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/mutable-map-of.html

var map = mutableMapOf<Int, String>(10 to "TEN", 20 to "TWENTY")
map
Enter fullscreen mode Exit fullscreen mode
{10=TEN, 20=TWENTY}
Enter fullscreen mode Exit fullscreen mode
map[10]
Enter fullscreen mode Exit fullscreen mode
TEN
Enter fullscreen mode Exit fullscreen mode
map[30] = "THIRTY"
Enter fullscreen mode Exit fullscreen mode
for(key in map.keys) {
    println(map[key])
}
Enter fullscreen mode Exit fullscreen mode
TEN
TWENTY
THIRTY
Enter fullscreen mode Exit fullscreen mode

HashMap

It is an implementation of the interface MutableMap

Documentation: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-hash-map/

var hmap: HashMap<Int, String> = HashMap<Int, String>();
// HashMap<Int, String>(initalCapacity) use this to reserve the memory while initilization
// you can add more keys later on
Enter fullscreen mode Exit fullscreen mode
hmap.put(1, "Spiderman")
hmap.put(2, "Ironman")
hmap.put(3, "Black Widow")
hmap.put(4, "Ant Man")
Enter fullscreen mode Exit fullscreen mode
hmap[1]
Enter fullscreen mode Exit fullscreen mode
Spiderman
Enter fullscreen mode Exit fullscreen mode
hmap.get(2)
Enter fullscreen mode Exit fullscreen mode
Ironman
Enter fullscreen mode Exit fullscreen mode
hmap.keys
Enter fullscreen mode Exit fullscreen mode
[1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode
for(key in hmap.keys) {
    println(hmap[key])
}
Enter fullscreen mode Exit fullscreen mode
Spiderman
Ironman
Black Widow
Ant Man
Enter fullscreen mode Exit fullscreen mode

hashMapOf

Documentation: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/hash-map-of.html

var hmap = hashMapOf<Int, Int>(1 to 10, 2 to 20)
hmap.size
Enter fullscreen mode Exit fullscreen mode
2
Enter fullscreen mode Exit fullscreen mode
for(key in hmap.keys) {
    println(hmap[key])
}
Enter fullscreen mode Exit fullscreen mode
10
20
Enter fullscreen mode Exit fullscreen mode

Sets

Documentation: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-set/#kotlin.collections.Set

Immutable Set: setOf

Documentation: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/set-of.html

var set1 = setOf(1, 2, 3, 4, 4, 2, 3)
set1
Enter fullscreen mode Exit fullscreen mode
[1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode
for(element in set1){
    println(element)
}
Enter fullscreen mode Exit fullscreen mode
1
2
3
4
Enter fullscreen mode Exit fullscreen mode
set1.contains(1)
Enter fullscreen mode Exit fullscreen mode
true
Enter fullscreen mode Exit fullscreen mode
set1.contains(10)
Enter fullscreen mode Exit fullscreen mode
false
Enter fullscreen mode Exit fullscreen mode

Mutable Set: mutableSetOf

Documentation: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/mutable-set-of.html

val set2 = mutableSetOf<Int>()
Enter fullscreen mode Exit fullscreen mode
set2.add(1)
set2.add(1)
set2.add(2)
set2.add(2)
set2.add(3)
Enter fullscreen mode Exit fullscreen mode
true
Enter fullscreen mode Exit fullscreen mode
set2
Enter fullscreen mode Exit fullscreen mode
[1, 2, 3]
Enter fullscreen mode Exit fullscreen mode
for(element in set2) {
    println(element)
}
Enter fullscreen mode Exit fullscreen mode
1
2
3
Enter fullscreen mode Exit fullscreen mode
set2.remove(1)
Enter fullscreen mode Exit fullscreen mode
true
Enter fullscreen mode Exit fullscreen mode
set2.remove(5)
Enter fullscreen mode Exit fullscreen mode
false
Enter fullscreen mode Exit fullscreen mode
for(element in set2) {
    println(element)
}
Enter fullscreen mode Exit fullscreen mode
2
3
Enter fullscreen mode Exit fullscreen mode

Hashset: hashSetOf

Documentation: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/hash-set-of.html

val set3 = hashSetOf<Int>(1, 2, 3, 5)
set3
Enter fullscreen mode Exit fullscreen mode
[1, 2, 3, 5]
Enter fullscreen mode Exit fullscreen mode
for(el in set3) {
    println(el)
}
Enter fullscreen mode Exit fullscreen mode
1
2
3
5
Enter fullscreen mode Exit fullscreen mode

Classes

Basic Example

Documentation: https://kotlinlang.org/docs/tutorials/kotlin-for-py/classes.html#declaration-and-instantiation

class Vehicle {
    // class properties
    var speed: Int = 0
    var wheels: Int = 0
    var model: String = ""

    // class methods
    fun SetModel(m: String) {
        model = m
    }

    fun SetSpeed(s: Int) {
        speed = s
    }
}
Enter fullscreen mode Exit fullscreen mode
var vehicle1 = Vehicle()
Enter fullscreen mode Exit fullscreen mode
vehicle1
Enter fullscreen mode Exit fullscreen mode
Line_166_jupyter$Vehicle@6400abd0
Enter fullscreen mode Exit fullscreen mode
vehicle1.model
Enter fullscreen mode Exit fullscreen mode
vehicle1.SetModel("BMW")
Enter fullscreen mode Exit fullscreen mode
vehicle1.model
Enter fullscreen mode Exit fullscreen mode
BMW
Enter fullscreen mode Exit fullscreen mode
vehicle1.wheels
Enter fullscreen mode Exit fullscreen mode
0
Enter fullscreen mode Exit fullscreen mode
vehicle1.wheels = 4
vehicle1.wheels
Enter fullscreen mode Exit fullscreen mode
4
Enter fullscreen mode Exit fullscreen mode

Nested Classes

Documentation: https://kotlinlang.org/docs/reference/nested-classes.html#nested-and-inner-classes

class C1 {

    fun ShowMe() {
        println("From Outer Class C1")
    }   

    class C2 {
        fun ShowMe() {
            println("From Inner Class C2")
        }
    }
}
Enter fullscreen mode Exit fullscreen mode
var c1 = C1()
c1.ShowMe()
Enter fullscreen mode Exit fullscreen mode
From Outer Class C1
Enter fullscreen mode Exit fullscreen mode
var c2 = C1.C2()
c2.ShowMe()
Enter fullscreen mode Exit fullscreen mode
From Inner Class C2
Enter fullscreen mode Exit fullscreen mode

Constructor

Documentation: https://kotlinlang.org/docs/reference/classes.html#constructors

Primary Constructor: Default

class Car {
    var wheels: Int
    var model: String

    init {
        println("Starting the car")
        wheels = 4
        model = "BMW"
    }

    fun Stop() {
        println("Stopping the car")
    }
}
Enter fullscreen mode Exit fullscreen mode
var car = Car()
Enter fullscreen mode Exit fullscreen mode
Starting the car
Enter fullscreen mode Exit fullscreen mode
car.wheels
Enter fullscreen mode Exit fullscreen mode
4
Enter fullscreen mode Exit fullscreen mode
car.Stop()
Enter fullscreen mode Exit fullscreen mode
Stopping the car
Enter fullscreen mode Exit fullscreen mode

Primary Constructor: Parameterized

class Vehicle(_wheels: Int, _model: String) {
    var wheels: Int
    var model: String

    init {
        println("starting")
        wheels = _wheels
        model = _model
    }

    fun Stop() {
        println("stopping")
    }
}
Enter fullscreen mode Exit fullscreen mode
var v1 = Vehicle(4, "BMW")
var v2 = Vehicle(2, "Kawasaki Ninka")
Enter fullscreen mode Exit fullscreen mode
starting
starting
Enter fullscreen mode Exit fullscreen mode
v1.wheels
Enter fullscreen mode Exit fullscreen mode
4
Enter fullscreen mode Exit fullscreen mode
v2.wheels
Enter fullscreen mode Exit fullscreen mode
2
Enter fullscreen mode Exit fullscreen mode
v1.Stop()
v2.Stop()
Enter fullscreen mode Exit fullscreen mode
stopping
stopping
Enter fullscreen mode Exit fullscreen mode

NOTE: Keyword init can be used multiple times

class InitOrderDemo(name: String) {
    val firstProperty = "First property: $name"

    init {
        println("First initializer block that prints ${name}")
    }

    val secondProperty = "Second property: ${name.length}"

    init {
        println("Second initializer block that prints ${name.length}")
    }
}

InitOrderDemo("hello")
Enter fullscreen mode Exit fullscreen mode
First initializer block that prints hello
Second initializer block that prints 5





Line_186_jupyter$InitOrderDemo@7435796a
Enter fullscreen mode Exit fullscreen mode

Secondary Constructor

Documentation: https://kotlinlang.org/docs/reference/classes.html#secondary-constructors

class Person {
    var name: String;
    var age: Int;

    constructor(name: String, age: Int) {
        this.name = name;
        this.age = age;
    }

    fun whoami() {
        println("I am $name and I am $age years old.")
    }
}
Enter fullscreen mode Exit fullscreen mode
var p1 = Person("John", 23)
var p2 = Person("Sarrah", 44)
Enter fullscreen mode Exit fullscreen mode
p1.whoami()
Enter fullscreen mode Exit fullscreen mode
I am John and I am 23 years old.
Enter fullscreen mode Exit fullscreen mode
p2.whoami()
Enter fullscreen mode Exit fullscreen mode
I am Sarrah and I am 44 years old.
Enter fullscreen mode Exit fullscreen mode

Visibility Modifiers

Documentation: https://kotlinlang.org/docs/reference/visibility-modifiers.html#classes-and-interfaces

class Person {
    private var name: String;

    constructor(name: String) {
        this.name = name
    }

    fun whoami(): String {
        return "I am $name"
    }
}
Enter fullscreen mode Exit fullscreen mode
var p1 = Person("Joel")
Enter fullscreen mode Exit fullscreen mode
p1.whoami()
Enter fullscreen mode Exit fullscreen mode
I am Joel
Enter fullscreen mode Exit fullscreen mode
p1.name
Enter fullscreen mode Exit fullscreen mode
Cannot access 'name': it is private in 'Person'
Enter fullscreen mode Exit fullscreen mode

Inheritance

Documentation: https://kotlinlang.org/docs/reference/classes.html#inheritance

open class Vehicle {

    public var wheels: Int = 0;
    public var model: String = "";

    fun Start() {
        println("Starting")
    }

    fun Stop() {
        println("Stop")
    }
}
Enter fullscreen mode Exit fullscreen mode
class Car: Vehicle {
    constructor(model: String, wheels: Int) {
        this.wheels = wheels
        this.model = model
    }
}
Enter fullscreen mode Exit fullscreen mode
var car = Car("BMW", 4)
Enter fullscreen mode Exit fullscreen mode
car.Start()
Enter fullscreen mode Exit fullscreen mode
Starting
Enter fullscreen mode Exit fullscreen mode
car.model
Enter fullscreen mode Exit fullscreen mode
BMW
Enter fullscreen mode Exit fullscreen mode
car.Stop()
Enter fullscreen mode Exit fullscreen mode
Stop
Enter fullscreen mode Exit fullscreen mode

Method Overriding

Documentation: https://kotlinlang.org/docs/reference/classes.html#overriding-methods

open class Vehicle {

    public var wheels: Int

    constructor(wheels: Int) {
        this.wheels = wheels
    }

    open fun Start() {
        println("Starting the vehicle")
    }

    open fun Stop() {
        println("Stopping the vehicle")
    }
}
Enter fullscreen mode Exit fullscreen mode
class Car(_wheels: Int): Vehicle(_wheels) {

    init {
        this.wheels = _wheels;
    }

    override fun Start() {
        println("Starting the car")
    }

    override fun Stop() {
        println("Stopping the car")
    }
}
Enter fullscreen mode Exit fullscreen mode
var car = Car(4)
car.wheels
Enter fullscreen mode Exit fullscreen mode
4
Enter fullscreen mode Exit fullscreen mode
car.Start()
Enter fullscreen mode Exit fullscreen mode
Starting the car
Enter fullscreen mode Exit fullscreen mode
car.Stop()
Enter fullscreen mode Exit fullscreen mode
Stopping the car
Enter fullscreen mode Exit fullscreen mode

Property Overriding

Documentation: https://kotlinlang.org/docs/reference/classes.html#overriding-properties

open class Shape {
    open protected val ndims: Int = 0

    fun getDims(): Int {
        return this.ndims
    }
}
Enter fullscreen mode Exit fullscreen mode
class Rectangle : Shape() {
    override protected val ndims = 4
}
Enter fullscreen mode Exit fullscreen mode
var rect = Rectangle()
Enter fullscreen mode Exit fullscreen mode
rect.getDims()
Enter fullscreen mode Exit fullscreen mode
4
Enter fullscreen mode Exit fullscreen mode
rect.ndims
Enter fullscreen mode Exit fullscreen mode
Cannot access 'ndims': it is protected in 'Rectangle'
Enter fullscreen mode Exit fullscreen mode

Abstract Class

Documentation: https://kotlinlang.org/docs/reference/classes.html#abstract-classes

abstract class Shape(_n: Int) {
    protected var ndims: Int

    init {
        this.ndims = _n
    }

    public fun getDims(): Int {
        return this.ndims
    }
}
Enter fullscreen mode Exit fullscreen mode
class Rect: Shape(4) {
}
Enter fullscreen mode Exit fullscreen mode
var rect = Rect()
rect.getDims()
Enter fullscreen mode Exit fullscreen mode
4
Enter fullscreen mode Exit fullscreen mode

Accessing super class from base class

open class Person {
    open fun sayHello() {
        println("Hello from super class")
    }
}

class Student: Person {
    constructor() : super() {}
    override fun sayHello() {
        println("Hello from sub class")
        super.sayHello()
    }
}
Enter fullscreen mode Exit fullscreen mode
var student = Student()
Enter fullscreen mode Exit fullscreen mode
student.sayHello()
Enter fullscreen mode Exit fullscreen mode
Hello from sub class
Hello from super class
Enter fullscreen mode Exit fullscreen mode

Data Class

Documentation: https://kotlinlang.org/docs/reference/data-classes.html#data-classes

data class Student(var name: String, var age: Int);
Enter fullscreen mode Exit fullscreen mode
var student: Student = Student("John", 22)
student
Enter fullscreen mode Exit fullscreen mode
Student(name=John, age=22)
Enter fullscreen mode Exit fullscreen mode
student.name
Enter fullscreen mode Exit fullscreen mode
John
Enter fullscreen mode Exit fullscreen mode
student.age
Enter fullscreen mode Exit fullscreen mode
22
Enter fullscreen mode Exit fullscreen mode

Sealed Class

Documentation: https://kotlinlang.org/docs/reference/whatsnew11.html#sealed-and-data-classes

sealed class Shape {
    data class Circle (var radius: Int)
    data class Rectangle (var width: Int, var height: Int)
    data class Square (var side: Int)
}
Enter fullscreen mode Exit fullscreen mode
var c = Shape.Circle(20)
c
Enter fullscreen mode Exit fullscreen mode
Circle(radius=20)
Enter fullscreen mode Exit fullscreen mode
var r = Shape.Rectangle(20, 10)
r
Enter fullscreen mode Exit fullscreen mode
Rectangle(width=20, height=10)
Enter fullscreen mode Exit fullscreen mode
var s = Shape.Square(20)
s
Enter fullscreen mode Exit fullscreen mode
Square(side=20)
Enter fullscreen mode Exit fullscreen mode

Extension Function

Documentation: https://kotlinlang.org/docs/reference/extensions.html#extension-functions

class Person {}

fun Person.sayHello(): String {
    return "Hello"
}
Enter fullscreen mode Exit fullscreen mode
var p = Person()
p.sayHello()
Enter fullscreen mode Exit fullscreen mode
Hello
Enter fullscreen mode Exit fullscreen mode

Generic Functions

Documentation: https://kotlinlang.org/docs/reference/functions.html#generic-functions

fun <T> Return(x: T): T {
    return x
}
Enter fullscreen mode Exit fullscreen mode
Return<Int>(5)
Enter fullscreen mode Exit fullscreen mode
5
Enter fullscreen mode Exit fullscreen mode
Return<String>("Hello")
Enter fullscreen mode Exit fullscreen mode
Hello
Enter fullscreen mode Exit fullscreen mode

Misc

Regex

Documentation: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/-regex/

var str = "Hello world at 10:22!!"
Enter fullscreen mode Exit fullscreen mode
var pattern = Regex("[0-9]{2}:[0-9]{2}")
Enter fullscreen mode Exit fullscreen mode
pattern
Enter fullscreen mode Exit fullscreen mode
[0-9]{2}:[0-9]{2}
Enter fullscreen mode Exit fullscreen mode
pattern.containsMatchIn(str)
Enter fullscreen mode Exit fullscreen mode
true
Enter fullscreen mode Exit fullscreen mode
pattern.findAll(str)
Enter fullscreen mode Exit fullscreen mode
kotlin.sequences.GeneratorSequence@53db2a04
Enter fullscreen mode Exit fullscreen mode

Call Java from Kotlin

Documentation: https://kotlinlang.org/docs/reference/java-interop.html

System.out.println("Hello")
Enter fullscreen mode Exit fullscreen mode
Hello
Enter fullscreen mode Exit fullscreen mode

Like Java, it also supports imports

Call Kotlin from Java

Documentation: https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html

filename: main.kt

fun main() {
}

fun Print() {
    println("Calling from kotlin file")
}
Enter fullscreen mode Exit fullscreen mode

filename: app.java

public class app
{
    public static void main() {
        MainKt.Print()
    }
}
Enter fullscreen mode Exit fullscreen mode

I hope you have learnt something new today. Follow the links to reach me

Top comments (8)

Collapse
 
krishisangaran profile image
krishi sangaran • Edited

Thanks for sharing this great article! Very easy to understand. Here I have drafted one more reference, It should be helpful for further process. blog.mirrorfly.com/build-android-c...

Collapse
 
citronbrick profile image
CitronBrick

Wow ! Really detailed article. Did not expect it to be so thorough, when I clicked it. Need the erstwhile Unicorn button for this.

Collapse
 
tbhaxor profile image
Gurkirat Singh

Hi @citronbrick, I am glad you liked it :D

Collapse
 
amy_ostler_a018096145a3d9 profile image
Amy Ostler

Hey dale

Collapse
 
gochev profile image
Nayden Gochev

best guide I have seen to date. Would love if you keep it updated.

Collapse
 
leminhduc1202 profile image
leminhduc1202

Awesome

Collapse
 
adnantanveer10 profile image
Adnan Tanveer

Please check out this app: dapks.com/afk-arena-mod-apk/
This is made in Kotlin. Can you please tell me how this app would be made in Kotlin.
Would really appreciate the help!

Collapse
 
amy_ostler_a018096145a3d9 profile image
Amy Ostler

Dale hey