avatarSiva Ganesh Kantamani

Summary

The web content provides an overview of advanced Android development topics, focusing on Kotlin and coroutines, and is part of a series aimed at preparing for Android interviews.

Abstract

The article is the third installment in a series dedicated to Android interview questions and answers, with a particular focus on Kotlin and coroutines. It delves into the advantages of Kotlin over Java, such as data classes, extension functions, null safety, and concise code, while also exploring Kotlin's advanced features like higher-order functions, reified types, and destructuring declarations. The article further explains when to use lateinit versus lazy initialization and discusses the open keyword, types of constructors, and scope functions. On the topic of coroutines, it covers the fundamentals of suspend functions, the differences between launch and async, dispatchers, and Kotlin Flow, providing insights into handling asynchronous operations efficiently. The content is designed to help Android developers understand complex concepts and prepare for technical interviews.

Opinions

  • The author emphasizes the importance of Kotlin's concise syntax and advanced features in modern Android development.
  • Kotlin's null safety is highlighted as a significant improvement over Java, reducing the occurrence of null-pointer exceptions.
  • The use of lateinit is recommended for mutable properties or those set externally, while lazy is preferred for properties that are only initialized once and are internally set.
  • Destructuring declarations are presented as a smart way to assign multiple values from objects or arrays, simplifying code.
  • Coroutines are strongly endorsed as a solution to the "callbacks hell" problem, offering a more streamlined approach to asynchronous operations.
  • The author suggests that understanding dispatchers is crucial for executing coroutine blocks on appropriate threads, optimizing performance and avoiding UI blocking.
  • The article concludes with a recommendation to read additional resources for a deeper understanding of advanced Android development topics.

Android Interview Questions and Answers — Part 3

Kotlin, and Coroutines

Photo by Headway on Unsplash

Android is one of the leading platforms in mobile development. If you want to reach millions of potential users, defiantly android would be at the top of your list. With this increasing hype, many software engineers choosing android development as their carrier choice.

Android interviews are a mix of many concepts like android basic to advanced concepts, Kotlin, coroutines, RxJava, Architectures, Design patterns, solid principles, and more. It’s highly impossible to include all of them in a single article. Following are the links to all the parts of this series, feel free checkout them.

In this part we’re going to explore the questions related to Kotlin, and corouties. Kotlin is preferred language to develop android app, Whereas coroutines are introduced to reduce the complexity of the code when use Rxjava to deal with complex asynchronous operations, but coroutines itself is an awesome & optimized approach to handle complex asynchronous operations.

Without any further delay, let’s get started:

Kotlin

Kotlin is a cross-platform language which opens the posibility to wide range of questions from basics things to complex use-cases such as higher order or inline functions. So let’s start from basics and try to cover as much as possible:

What are the advantages of Kotlin over Java?

Note: This is the most basic question asked in any interview. The answer to this question varies from developer to developer based on their hands on experience with Kotlin.

Basically my version to this questions starts is — Kotlin code is more concise and takes less time & thinking to write the same code in Java. Following are the few advantages that I like the most in Kotlin over java:

  • Data classes: With the help of Kotlin data classes we no longer need to deal with hash code comprisions, getters & setters and more. A quick solution a common use-case.
  • Extension Functions: This feature open gates to the next level of android development. I mostly use this feature to create reusable code and reduce as much code as possible at the call site.
  • Null Safety: No matter how hard you try, there will always be a null pointer expression. With the easy declaration of Kotlin nullable values, the compilation error of possible null-pointer exceptions and the Elvis operator to avoid them made Kotlin became one of the best languages to minimize the nullpointerException.
  • Keywords like object, open, inline, etc helps to avoid boiler-plate code
  • Where as named parameters, higher-order functions, primary constructors, etc comes handy in common use-cases of android development.

To learn more about Kotlin and perform well in android interviews read my series of Advanced development with Kotlin:

What’s a const? How does it differ from a val?

By default val properties are set at runtime, adding const modifier to it makes it a compile time constant. Moreover a const cannot be used with a var or on its own & it’s not applicable on a local variable.

What is higher order function?

In Kotlin, a function can be passed as a parameter or can be returned from a function, the function which does the same is known as a higher-order function. In other words, a higher-order function is a function that takes functions as parameters or returns a function.

What is reified?

Sometimes we need to access the type of the parameter inside the functions, especially inline functions. In this case, we need to add a reified modifier to the type so we’ll have the ability to access it in the body and use comparission operators like is and as on it.

inline fun <reified T> TreeNode.findParentOfType(): T? {
    var p = parent
    while (p != null && p !is T) {
        p = p.parent
    }
    return p as T?
}

When to use lateinit over lazy initialization in Kotlin?

There are some simple rules to determined if you should use one or the other for properties initialization:

  • If properties are mutable (i.e. might change at a later stage) use lateInit
  • If properties are set externally (e.g. need to pass in some external variable to set it), use lateinit. There’s still workaround to use lazy but not as direct.
  • If they are only meant to initialized once and shared by all, and it’s more internally set (dependent on variable internal to the class), then use lazy. Tactically, you could still use lateinit, but using lazy would better encapsulate your initialization code.

What are destructuring declarations in Kotlin? Explain it with an example?

Destructuring Declarations is a smart way to assign multiple values to variables from data stored in objects/arrays.

val book = Book("name", "author")
val(name, author) = book

Explain about open keyword in Kotlin?

The open keyword means “open for extension“. The open annotation on a class is the opposite of Java’s final: it allows others to inherit from this class.

What are the types of constructors in Kotlin?

Constructors in Kotlin are of two types:

  • Primary — These are defined in the class headers. They cannot hold any logic. There’s only one primary constructor per class.
  • Secondary — They’re defined in the class body. They must delegate to the primary constructor if it exists. They can hold logic. There can be more than one secondary constructors.

How to check the null status of latintent variable?

lateinit var file: File
if (::file.isInitialized) { ... }

Explain the difference between scope functions in Kotlin?

This is one of the question that I face on almost all interviews and I intended to ask when I was on the other side of the table. Read more about scope functions from here.

Coroutines

Kotlin Coroutines are recommended approach to work with asynchronous operations in android development. Coroutines provide an easy way to execute complex operations. For example when we try to execute an API request via RxJava then we need to add call backs to listen success and error responses. But with coroutines, we can be free of callbacks hell because Coroutines provides a way to execute asynchronous operations sequentially.

What is suspend?

Note: This a very basic question that shows your fundamental skills of coroutines. Suspend is a modifier used on functions to tell this is a coroutine function.

What is the difference between launch and async?

Launch is a method in CoroutineScope which starts a coroutine without blocking the current thread and returns a reference to the coroutine as a Job(which can be canceled to stop the execution of that coroutine).

Whereas Async is a method in CoroutineScope that starts a coroutine and returns its future result as an implementation of Deferred.

Explain about dispatchers in coroutines?

Dispatchers are nothing but a bunch of keywords that are used to tell coroutines on which thread it should operate. We can execute multiple blocks of code in a coroutine on multiple threads just by changing the dispatcher.

There are three types of dispatchers

  • Default: Anything that takes too long to run on the main thread should run on default dispatcher, like executing DiffUtil.
  • IO: Tasks like writing a file or making an API call should happen on the IO dispatcher, which blocks the UI.
  • Main: This is the main thread, where all the tasks in Android usually execute. You can start on this thread by default and change the dispatcher wherever you need it.

How to switch dispatchers in coroutines?

We need to use withContext to switch between dispatchers.

runBlocking(Dispatcher.Main) {
      log("Started in Dispatcher.Main")
      withContext(Dispatcher.IO) {
          log("Working in Dispatcher.IO")
      }
      log("Back to Dispatcher.Main")
}

Explain about Job and SupervisorJob?

A background job that can be arranged in a parent-child hierarchy. Cancellation of any parent will lead to the cancellation of all its children immediately, and failure or cancellation of any child jobs other than CancellationException lead to cancellation of its parent.

Whereas a supervisor job is just a job, but its children can fail independently without taking down its parent.

Explain about Kotlin Flow?

Note: This a high-level question which you will face rarely, if the company code base heavily based on steam of asynchronously operations they might ask about Kotlin flow.

Flow API in Kotlin is a better way to handle the stream of data asynchronously that executes sequentially. We need to use flowon function to determine on which thread it should execute. To observe the data we need to use collect or collectLatest.

Bonus

To learn more about Android advanced development read the following articles:

I came across this article recently published by Satya Pavan Kantamani about Data-binding in Android. Excellent piece of work, highly recommended

That is all for now, hope you learned something useful, thanks for reading.

AndroidDev
Interview Questions
Kotlin
Coroutine
Coffee2021
Recommended from ReadMedium