/images/profile.jpg

Mohsen Biglari

Typealias vs. inline value class

Normally, Typealias and inline value class (which I’ll refer to as value class throughout this text) are utilized for different purposes. However, developers might occasionally use one for the other. Let’s explore some examples and clarify the differences. Typealias kotlinlang.org does a pretty good job explaining Typealias: Type aliases provide alternative names for existing types. If the type name is too long you can introduce a different shorter name and use the new one instead.

A smarter way of testing Coroutines with runTest

Testing coroutine-based code in Kotlin can be challenging due to its asynchronous nature. Fortunately, Kotlin’s kotlinx.coroutines library provides helpful utilities for testing, including the runTest function. Let’s dive into how to effectively use runTest and streamline coroutine testing in your Kotlin projects. runTest You’re probably used runTest before. Let me quote kotlinlang.org: Executes testBody as a test in a new coroutine, returning TestResult. On JVM and Native, this function behaves similarly to runBlocking, with the difference that the code that it runs will skip delays.

A handy Kotlin coroutine extension for switching dispatcher

Imagine you have a suspend function like this: 1 2 3 suspend fun doSomething() = withContext(Dispatchers.IO) { // body } This looks alright. Using withContext every time looks a bit verbose though. There’s a nifty Kotlin extension on the invoke function that simplifies the code and makes it cleaner. 1 2 3 4 5 import kotlinx.coroutines.invoke suspend fun doSomething() = Dispatchers.IO { // body } The invoke extension allows you to specify the dispatcher directly within the function call, eliminating the need for withContext.