What are coroutines in Kotlin and how to write them

Posted on September 21st, 2020

Kotlin is part of the new generation of languages that are gently gaining big traction against big names like Java and C++. Kotlin was designed and developed by JetBrains as an open source and statically typed programming language. Over the past few years, Kotlin has grown to become the main language of choice for Android developers, with Google advocating for it over Java nowadays.

The idea of coroutines is not new. It’s a concurrency pattern that allows you to achieve multiple processes at once. Coroutines can be found in JavaScript, Java, Clojure, C+, C++, PHP, Python, Ruby, and Swift, to name a few.

However, they may not be called a ‘coroutine’ directly, but the fundamentals of what a coroutine achieves is similar, if not exactly the same. Kotlin’s ideological implementation of coroutines borrows heavily on these languages that have an established experience in it.

But what is a coroutine?

Async, coroutine, concurrency

A coroutine can be broken into two parts – co and routines. The co part represents the word cooperative and routines refers to functions.

Kotlin works in a serial fashion, meaning that a function cannot move forward if it relies on another function to give it some signal or data. The control flow shifts to the second function, giving it total power and the ability to hold an application hostage. You cannot negotiate the power away from the second function, making the process of running your app tightly coupled to the expected return.

With the introduction of coroutines, Kotlin is able to implement asynchronous code and achieve concurrency. This means that your Kotlin code has the ability to form layers, allowing for things to run in parallel with each other.

Cooperative functions become a possibility for Kotlin as coroutines allows the transfer of control via exit points, allowing for effective recursive loops to occur.

Why are coroutines a big deal in Kotlin?

In part, it’s because coroutines are cheaper when it comes to memory than threads, making it more efficient on the machine it’s expected to run on.

For Kotlin, coroutines lets you write asynchronous and non-blocking code (that is, your code can continue to execute without having to stall and wait for things to complete).

How to write coroutines in Kotlin

Setting up coroutines

In IntelliJ IDEA, start up a new Gradle project and follow through with the wizard set up. In your build.gradle file, you need to make sure it’s configured for Kotlin 1.3 or higher. Coroutines isn’t supported in previous versions before Kotlin 1.3.

Your plugins settings should look something like this:

 plugins {
     kotlin("multiplatform") version "1.4.0"
 }

It’s good to note that multiplatform can be replaced by other targets such as the jvm or js for JavaScript. For now, multiplatform will work for the purposes of this tutorial.

Coroutines is a library in Kotlin. This means that you’ll need to import it as a dependency. Here’s a sample code of what that looks like:

dependencies {
    ...
     implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.9"
 }

Implementing this dependency will bring in kotlinx.coroutines library. You also need to add it to Bintray JCenter repository.

repositories {
     jcenter()
 }

Now you can start writing your coroutines inside src/main/kotlin

But what exactly does a coroutine look like?

In a way, it’s like a light-weight thread. It can run in parallel, wait and communicate to each other. The easiest way is to think of them as functions that can be run in an asynchronous manner.

The major difference between coroutines and threads is to do with how memory is allocated. Coroutines simply has a cheaper memory allocation, therefore making more efficient by default.

Writing coroutines in Kotlin

Let’s pretend we have an orders list that we can fetch using an API. So the function used to fetch the data can look something like this:

fun fetchOrders(){
     val array = api.fetchOrdersList()
     updateUI(array)
 }

If you do this on the main thread, your app will certainly crash. Another way is to wrap this inside a thread. Then you start facing a life-cycle management issue. So we start using callbacks with subscriptions.

Next thing we know, we end up with code that looks like this:

fun onDescript(){
     subscription1.cancel()
     subscription2.cancel()
     subscription3.cancel()
     subscription4.cancel()
 }

It’s a special kind of callback hell – long, unnecessary and somewhat tedious. Coroutines solves in Kotlin what async support did to JavaScript. It runs in the background as lightweight threads while allowing you to execute tasks relating to the background or UI changes.

Writing a coroutine using suspend

To turn your function into a coroutine, use suspend.

suspend fun fetchOrders(){
     val array = api.fetchOrdersList()
     updateUI(array)
 }

And that’s it.

You might be asking yourself – surely, there has to be more to it than this. Indeed, you are correct.

Writing a coroutine using withContext

You can also write a coroutine using withContext, which will let you specify which thread you want to execute on. Kotlin has three types of dispatchers available and they are:

  • Default –  anything that takes too long on the main thread gets shifted into the default dispatcher. It’s the fallback thread rather than the starting thread.
  • IO – great for writing a file or making API calls
  • Main – this is the thread where Android usually executes and is the starting default.

So writing your coroutine using withContext looks something like this:

fun fetchOrders(){
     withContext(Dispatchers.IO){
        val array = api.fetchOrdersList()
        updateUI(array)
    }
 }

Writing a coroutine using launch

Alternatively, you can write a coroutine using launch. What launch does is start a coroutine without blocking the current thread and returns a reference to the coroutine as a Job. Jobs can be cancelled if required to stop the execution of that particular coroutine.

Writing launch looks something like this:

  launch {
      val array = api.fetchOrdersList()
      updateUI(array)
 }

By default, this will run on main and the context of the parent. You can specify dispatchers to determine which thread your launch coroutine runs on. This can look something like this:

   launch(Dispatchers.IO){
      val array = api.fetchOrdersList()
      updateUI(array)
 }

How to cancel a coroutine

At some point, you might want to cancel the coroutine because you don’t need it anymore. It’s important that you cancel any coroutine you’re not using because it helps free up resources from unnecessary socket connections.

We have three flags that we can use to verify the status of a coroutine and they are:

  • isActive – will return true if the function is still completing the states of a coroutine
  • isCompleted – is false by default and will flip to true when all the parent and child jobs are completed
  • isCancelled– this is also false by default unless an exception occurs or you cancel it. Only when one of these two things happen, it will flip to true.

Canceling a coroutine looks something like this:

//hypothetical coroutine setup
 val scope = CoroutineScope(parentJob)
 val customerListJob = scope.launch{ ... }
 val orderListJob = scope.launch{ ... }
 ​
 //canceling coroutines in the scope
 scope.cancel()

Parting thoughts

That’s the basics of coroutines, what they are, how they work and how to write them.

If you’re already familiar with concepts like async and concurrency, writing coroutines should be a simple task to pick up. The alternative to achieving asynchronous in Kotlin is to use RxJava – a library that allows for easier termination of subscriptions when activities end.

Terminating subscriptions is something we all learn early on to prevent memory leaks and wasted resources. This is one of RxJava‘s jobs. The same idea can be applied to coroutines. While the scale and severity is not as high when it comes to coroutines, it’s still good practice to make sure that your coroutines are cancelled properly.

While the idea of coroutines is not exactly revolutionary or new, it’s implementation in a Kotlin context is. The ability to use coroutines in Kotlin means that the language has another tool up its curly braces for us to use. Any additional functionality and features that are based on time tested methodologies is a welcomed addition when it comes to Kotlin.

Kotlin Multiplatform: The secret to Kotlin’s rising popularity

Posted on September 9th, 2020

Kotlin is quickly becoming one of the most popular programming languages. Most programming bloggers now recommend Kotlin as one of the must learn languages of 2020.

But before we go into why this makes Kotlin multiplatform special, we need to dig into what multiplatforming is.

What is multiplatform?

The idea of multiplatform is not new. It applies only to the compilation time and once that process is completed, nothing else really matters.

Unlike scripting languages like JavaScript, Python, and Ruby, Kotlin is a programming language. This means that there is no pre-existing interpreter available to turn your code into what you want it to be. A programming language is executed differently from what we’re used to, if you’re coming in from a web development perspective.

When we say the words ‘mobile’ and ‘multiplatform’ in the same sentence, we often associate with third party libraries and frameworks that create structures that wrap around the code to create native applications. However, if you look at the actual code, it’s all still JavaScript under the hood.

Non-browser based applications are a bit different and require translation to run on the machine it exists on. The exe files you see on your computer is a packaged set of translated source code that is compatible for your particular device. This translated code often boils down into machine code.

For multiplatform scripted-based outputs, the wrapper often creates a mini translator

For multiplatform scripted outputs, the wrapper often creates a mini interpreter to make your produced view possible. The code is not truly ‘native’, in that the actual code is sitting inside a generated construct that’s forcing it to work. Kotlin, however, creates true native code and is able to separate itself from platform specific things.

Commitment is pricey, Kotlin reduces it

For a lot of other multiplatform languages, frameworks, and libraries out there, the act of committing to it can be a costly exercise. In part, it’s because they tend to lock you into their ecosystem. This means if you code in something like React Native or Flutter, your entire app is often stuck inside it. It’s the same with wrapper JavaScript based libraries.

You can’t exactly pick and choose what goes where.

Not only that, when using React Native or Flutter you’re often tied to certain UI restrictions and accessibility to native platform features are limited based on the language, library or framework’s support and the size of its ecosystem. This means that if that if your particular chosen language falls out of favor, or the ecosystem doesn’t grow as quickly as you need to in order to cover new features and functionalities, you become instantly disadvantaged.

This is why Kotlin is different to Flutter, for example. Kotlin doesn’t lock you in through an entire application. It focuses on a logic first approach, meaning that your application’s business layer is cleanly separated from the UI. This is important because modern applications tend to focus on a UI first approach, with business logic and rules tightly coupled into the interactions.

This causes a problem for creating truly multiplatform apps, especially in the mobile space. There are major differences in native UI defaults between iOS and Android, and navigating between the two can be difficult. When the code becomes tightly coupled with the UI, it requires sweeping changes to make it compatible and efficient for that particular platform.

Kotlin’s multiplatform approach creates an enforced modularization, forcing you to write your applications in a way that shields you from the allure of creating pixel perfect widgets. Rather, you are thinking about how all the pieces are going to fit together, dealing with how to call in external services, querying APIs, organizing returned data, and dealing with the kinds of interactions you want to achieve.

While the UI is the thing that interfaces with the user and creates the most impact, an app’s ultimate usefulness is determined by the logical rules it wants to implement. The separation of UI and logical layer makes Kotlin a less risky option than fully committing to something like React Native, because you can pick and chose what you want and integrate it with native app languages if required.

Kotlin’s allowance for hybridization results in a flexible migration for existing applications, whilst creating a high level of reusability between different types of developers. This is a useful feature for when we operate in two separate teams – one of Android and one for iOS – as it allows developers to share knowledge domains and reduce duplication of native code.

How to write a Kotlin code in Android Studio

Kotlin is the common code between Android and iOS. However, you might want to work with your Kotlin code in Android Studio. Here’s a quick guide on how to get started with Kotlin in Android Studio – which is an alternative and free way of creating Kotlin code.

First, open up your Android Studio, click on Configure and select Plugins.

android studio tutorial

Select Marketplace and search for KMM. This stands for Kotlin Multiplatform Mobile.

kotlin kmm

Once that’s done, it’ll prompt you to restart the IDE. Start a new Android Studio Project and in the Select a project Template section, select KMM Application.  You might need to scroll down to the bottom to find it.

select a project template

Give your project a name, select the minimum SDK support, save location and package name.

config your project

Click on the finish button and viola! You now have the barebones set up for Kotlin.

edit system environment variables

This setup is for writing an entire mobile app in Kotlin. However, if you only want to write libraries, Visual Studio Code also has a plugin that supports Kotlin.

Setting up Kotlin in Visual Studio Code

To get Kotlin to work in Visual Studio Code, you’ll need two plugins: Kotlin Language and Code Runner. Open up your VS Code, head over to plugins and install it.

Next, add Kotlin and Java to PATH. This will let you run Kotlin and Java from the command line. To add a PATH, do the following:

  • Open Start Search and type in env. Choose Edit the system environment variables.
edit system environment variables
  • This will bring up the System Properties panel. Select Environment Variables.
settings
  • This will bring up a new panel. Under System variables, scroll down until you find Path. Click on edit.
  • Add the following paths to your environment variables (or where you saved it):
    • C:Program FilesJetBrainsIntelliJ IDEA Community Edition 2019.1.3pluginsKotlinkotlincbin
    • C:Program FilesJavajdk-12.0.1bin

You can now run Kotlin in VS Code. To test that everything works, create a new folder with main.kt. Here’s a simple function to get you started:

 fun main(){
     println("it works! Do a happy dance.");
 }

To run your code, right click on the main function and select run code. Your code should compile and execute. During this process, you’ll also see an additional main.jar file.

Final thoughts

That’s basically it to get set up with Kotlin. Multiplatform itself is a concept that applies at compile time. However, Kotlin does it better than other options out there by creating a system that allows you to keep your Kotlin code modular and not locked into a particular way of writing your app.

When you write in Kotlin, there’s no heavy lifting required to transition or migrate your applications out. It’s compilation process also means that you’re not going to run into problems that JavaScript based applications have with memory, threading, and third party plugin compatibility.

20 Kotlin interview questions for junior and senior developers

Posted on November 21st, 2019

Kotlin Interview Questions

Android boasts the largest smartphone OS market share, as it currently sits at 76%, while predictions say that it will grow in the future. 

This means that building an Android app can be a successful and lucrative business idea. 

But, for translating this idea into a reality, you need a well-versed and skilled Kotlin developer or a dev team. Kotlin is a general-purpose programming language and as of May 2019, it’s a preferred choice of Android app developers.

Just like Angular.JS is one of the most powerful and useful front-end frameworks for developing web apps – here’s a list of Angular interview questions in case you need someone to help you create amazing UI, the same can be said for Kotlin when it comes to building Android apps. 

However, business owners and HR professionals who are in charge of the screening, interviewing, and hiring process are rarely development experts. This means they aren’t familiar with the nitty-gritty of development from a technical perspective, which can result in their failure to focus on a particular set of skills and characteristics vital for a good Kotlin developer. 

This guide will help you navigate your interviews and identify your ideal hire, and if you need a break for interview questions there are also a few job interview memes to keep you entertained, we aim to please, after all.

job interview questions funny

Interview Questions and Answers for Junior Kotlin Developers

These couple of questions will help you pick a junior developer who’s the right fit for your project. Given that they would work under the supervision of senior Kotlin developers and execute the tasks given by them, it’s essential to understand that your new hire doesn’t have to be an expert in the field but someone with the potential to learn and grow. 

1: What is Kotlin?

A: Kotlin is a statically-typed language that runs on the Java Virtual Machine. It can seamlessly interoperate with Java and is considered an alternative to the standard Java compiler. 

2. Is Kotlin better than Java? 

A: It’s simpler and much cleaner than Java, as it’s more concise and uses fewer lines of code in order to solve the same problems. Besides being generally more efficient and effective, Kotlin is safer in the sense that it prevents certain common coding errors. As a result, there are fewer app crashes and system failures. Kotlin comes with some features that aren’t available in Java, such as smart casts, operator overloading, data classes, null safety, coroutines, to name just a few. 

3. What are extension functions in Kotlin?

A: It’s a mechanism that allows extending a class without the need to inherit from the class or use Decorator or other design patterns. 

4. What is null safety? 

A: This is a feature that prevents a null reference exception, the equivalent of Java’s NullPointerException in real time. 

kotlin job interview questions meme

5. Is there a ternary operator like in Java? 

A: No, there isn’t, but what a ternary operator does can be achieved through an if-else expression. 

6. What’s the difference between val and var in Kotlin?

A: Both are used for declaring a variable. However, while val is a final variable that is immutable and can be initialized only once, var is a general variable that can be assigned multiple times. 

7. What are the basic data types in Kotlin? 

A: Numbers, characters, Booleans, arrays, and strings. 

8. How many constructors are there in Kotlin? 

A: A constructor’s main role is to initialize the properties of a class. In Kotlin, there can be a primary constructor and one or more secondary constructors. 

9. What are the extension methods that Kotlin provides to the Java.io file list? 

A:

  • bufferedReader():read contents of a file to BufferedReader
  • readBytes() : read contents of a file to ByteArray
  • readText(): read contents of a file to a single String
  • forEachLine() : read a file line by line in Kotlin
  • readLines(): read lines in a file to List

10. What are the structural expressions in Kotlin? 

A: There are three structural expressions:

  • Return: helps to return from the closest function or an anonymous function. 
  • Break:  helps to terminate the closest enclosing loop. 
  • Continue: helps proceed to the next step of the closest enclosing loop. 

Interview Questions and Answers for Senior Kotlin Developers 

If you need to hire a more experienced Kotlin developer, here are some questions that can help you pick the one that will be able to run your project properly and monitor junior developers. 

1. What is the difference between const and val? 

A: Const is a keyword used to define compile-time constants, while val is used to define runtime constants. 

2. Is it possible to migrate code from Java to Kotlin? 

A: Yes, it is. IntelliJ IDEA is a tool that can help you do that. 

3. What are data classes in Kotlin?

A data class is similar to a regular class with certain additional functionalities. For example, in order to store data items in Java, it’s necessary to create a class by setting the variables. In Kotlin, all it takes is adding keyword data to the class, and the compiler will automatically generate a default getter and setter. So, basically, there’s no need to write or generate the extensive boilerplate code. 

4. What modifiers are available in Kotlin?

A: Kotlin offers four visibility modifiers:

  • Private: visible inside this class and all its members only.
  • Protected: the same as private, but visible in subclasses too.
  • Internal: visible inside the same module 
  • Public: by default, all the declarations are visible to everyone. 

5. What is a string in Kotlin? 

A:  It’s a basic data type. Strings are immutable and Kotlin has two types of string literals: 

  • Raw strings, which are delimited by a triple quote and can contain newlines, arbitrary text, and any other character.   
  • Escaped strings, which handle special characters by escaping them. 

6. What is the Init Block?  

A: It’s the initializer block and the code inside of it is executed when the primary constructor is instantiated. 

7. Is new a keyword in Kotlin? 

A: No, it’s not and it doesn’t have to be used to instantiate a class. 

8. Are there primitives in Kotlin? 

In a nutshell, there are no out-of-the-box primitives in Kotlin – they can’t be created at a code level. Given that Kotlin has been designed to cooperate with Java and the JVM seamlessly, certain types like int or float can act like primitives in certain cases. 

9. Is there an equivalent for switch in Kotlin?

A: Yes, there is. The When keyword is used instead. 

10. What are deconstructing declarations? 

A: Kotlin comes with a functionality that allows developers to assign multiple values to variables. This kind of syntax allows for creating multiple variables that can be used independently at once.

These 20 questions can help you sift through a large number of Kotlin dev applicants and find the one who’ll help you build amazing Android apps.