Skip to content

Instantly share code, notes, and snippets.

Avatar

Stephan Oudmaijer soudmaijer

View GitHub Profile
View ScopingFunctions.kt
fun using_with() {
val stringBuilder = StringBuilder()
stringBuilder.append("Hello")
stringBuilder.append(", Kotlin!")
print(stringBuilder.toString())
}
fun using_also(a: Int): Int {
val b = a * 10
if (b > 100) print(">100")
View Exercise1.kt
import java.io.IOException
fun bar() {
throw IOException()
}
View SpringBootFlowExample.kt
package nl.sourcelabs.kotlinflowboot.server
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.http.MediaType
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
View ReplaceSleepWithDelay.kt
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
suspend fun loadImage200(name: String) {
delay(2000) // simulate slow behaviour
}
fun loadImage404(name: String) {
throw RuntimeException("Image not found: $name")
View CoroutineScope.kt
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
fun main() {
lateinit var a: Deferred<Nothing>
lateinit var b: Deferred<Unit>
View RemoveGlobalScope.kt
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import java.lang.Thread.sleep
fun main() {
val a = GlobalScope.async { throw RuntimeException() }
val b = GlobalScope.async { delay(2000).also { println("I leaked!") } } // Will not be printed!
View LeakingCoroutine.kt
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import java.lang.Thread.sleep
fun main() {
val a = GlobalScope.async { throw RuntimeException() }
val b = GlobalScope.async { delay(2000).also { println("I leaked!") } } // Will not be printed!
View ImproveWithAsync.kt
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlin.system.measureTimeMillis
suspend fun loadImage(name: String) {
println("Loading image: $name...")
delay(2000) // simulate slow behaviour
println("Done loading image: $name.")
}
View Exercise16.kt
fun main() {
val address1 = Address(postalCode = "1506TX", houseNumber = "4")
val address2 = address1.copy()
println("address1 == address2: ${address1 == address2}")
val address3 = address1.copy()
address3.street = "Hermitage 4"
println("address1 == address3: ${address1 == address3}")
View Exercise15.kt
class Product(val ean: String, val title: String)
class Book(val publisher: String, val author: String)
fun main() {
val book = Book(
ean = "9781617293290",
title = "Kotlin in Action",
publisher = "Manning",
author = "Dmitry Jemerov, Svetlana Isakova"