Kotlin Basics

Kotlin Class Extensions

fun Int.addFive() : Int {
    return this + 5
}

When are Class Extensions Useful in Ktor?

Coroutine Contexts

Sample Code:

import kotlinx.coroutines.*
import kotlin.random.Random

fun main(args: Array<String>) = runBlocking {
    // 64 Threads in IO
    withContext(Dispatchers.IO) {
        repeat (100_000) { // 100_000 = 100,000
            launch {
                firstcoroutine(it) // 'it' will be the current iteration
            }
        }
        println("End of withContext")
    }
    println("End of main function")
}

suspend fun firstcoroutine(id: Int) {
    delay(Random.nextLong()%2000) // The delay is a random number less than 2 seconds
    println("first $id")
}

Running this code gives an output something like:

first 0
first 1
first 2
first 5
first 6
first 7
first 8
first 10
first 9
first 11
first 13
...

Notice how the sequence falls out of order? This is threading and Kotlin coroutines in action.


Revision #1
Created 17 April 2022 00:20:30 by Elkip
Updated 17 April 2022 01:02:09 by Elkip