Kotlin Interview Questions for Developers

Use our engineer-created questions to interview and hire the most qualified Kotlin developers for your organization.

Kotlin

Known primarily for its use in Android development — Google announced it as an official Android language in 2017 — Kotlin is also popular for its Java interoperability, concise syntax, and null safety type system.

According to the CoderPad 2024 Developer survey, Kotlin is the 13th most in-demand language among technical recruiters and hiring managers.

We have designed functional coding assignments and interview queries specifically aimed at assessing developers’ Kotlin expertise during coding interviews. Moreover, we have assembled a collection of recommended guidelines to guarantee that your interview questions effectively measure the candidates’ proficiency in Kotlin.

Table of Contents

Kotlin example question

Help us design a parking lot

Hey candidate! Welcome to your interview. Boilerplate is provided. Feel free to change the code as you see fit. To run the code at any time, please hit the run button located in the top left corner.

Goals: Design a parking lot using object-oriented principles

Here are a few methods that you should be able to run:

  • Tell us how many spots are remaining
  • Tell us how many total spots are in the parking lot
  • Tell us when the parking lot is full
  • Tell us when the parking lot is empty
  • Tell us when certain spots are full e.g. when all motorcycle spots are taken
  • Tell us how many spots vans are taking up

Assumptions:

  • The parking lot can hold motorcycles, cars and vans
  • The parking lot has motorcycle spots, car spots and large spots
  • A motorcycle can park in any spot
  • A car can park in a single compact spot, or a regular spot
  • A van can park, but it will take up 3 regular spots
  • These are just a few assumptions. Feel free to ask your interviewer about more assumptions as needed

Junior Kotlin interview questions

Question: What is the difference between val and var in Kotlin? Provide an example to demonstrate their usage.

Answer: In Kotlin, val is used to declare a read-only (immutable) variable, while var is used to declare a mutable variable. Once initialized, the value of a val cannot be changed, whereas a var can be reassigned.

val pi = 3.14
var radius = 5.0

radius = 7.0 // Valid: radius is mutable and can be reassigned
pi = 3.14159 // Invalid: pi is read-only and cannot be reassignedCode language: JavaScript (javascript)

Question: In the given Kotlin code, there is an error preventing the function from executing correctly. Identify the error and provide a fix.

fun printMessage() {
    println(message)
    val message = "Hello, World!"
}

printMessage()Code language: JavaScript (javascript)

Answer: The error is due to the usage of the message variable before it is declared. To fix the error, move the declaration of message before the println statement.

fun printMessage() {
    val message = "Hello, World!"
    println(message)
}

printMessage()Code language: JavaScript (javascript)

Question: Explain the concept of nullable types in Kotlin and how to safely handle null values.

Answer: Nullable types in Kotlin allow variables to hold either a non-null value of the declared type or a special value called null. To safely handle null values, Kotlin provides two main approaches: null checks and safe calls.

Null checks involve verifying if a nullable variable holds a non-null value before accessing its properties or calling its methods. This can be done using the safe access operator ?. or the not-null assertion operator !!.

Safe calls, denoted by the ?. operator, enable executing a statement only if the variable is non-null. If the variable is null, the expression returns null without throwing an exception.

val nullableString: String? = null

val length = nullableString?.length // Returns null if nullableString is null

nullableString?.let { str ->
    println(str.length) // Executed only if nullableString is non-null
}Code language: JavaScript (javascript)

By utilizing null checks and safe calls, developers can handle null values safely and prevent NullPointerExceptions.

Question: Explain the purpose of the lateinit modifier in Kotlin and provide an example of its usage.

Answer: The lateinit modifier is used in Kotlin for properties that are declared without an initial value but are guaranteed to be initialized before they are used. It allows the property to be accessed directly without nullable checks or assignment checks.

Here’s an example:

class Person {
    lateinit var name: String

fun initializeName() {
        name = "John Doe"
    }

fun printName() {
        if (::name.isInitialized) {
            println(name)
        }
    }
}

val person = Person()
person.initializeName()
person.printName() // Output: John DoeCode language: JavaScript (javascript)

In this example, the name property is declared with lateinit as it will be initialized later in the initializeName function. The printName function can directly access the name property without null checks due to the guarantee that it will be initialized before use.

Question: Explain the difference between List and MutableList interfaces in Kotlin.

Answer: In Kotlin, List and MutableList are interfaces representing read-only and mutable lists, respectively.

List is an interface that provides read-only access to a collection of elements. Once created, the elements of a List cannot be modified. The List interface provides operations like accessing elements by index, checking size, iterating over elements, and more.

val readOnlyList: List<String> = listOf("Apple", "Banana", "Orange")
println(readOnlyList[0]) // Output: Apple
readOnlyList.add("Grapes") // Error: Cannot modify a read-only listCode language: JavaScript (javascript)

MutableList, on the other hand, is an interface that extends List and provides additional operations to modify the collection, such as adding, removing, or updating elements.

val mutableList: MutableList<String> = mutableListOf("Apple", "Banana", "Orange")
mutableList.add("Grapes")
println(mutableList) // Output: [Apple, Banana, Orange, Grapes]Code language: JavaScript (javascript)

Using MutableList, you can dynamically modify the list by adding, removing, or updating elements after its creation.

Question: Explain the concept of higher-order functions in Kotlin and provide an example.

Answer:

Higher-order functions in Kotlin are functions that can accept other functions as parameters or return functions as results. They allow developers to treat functions as first-class citizens, enabling powerful functional programming techniques.

Here’s an example of a higher-order function:

fun calculate(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
    return operation(a, b)
}

val addition = { x: Int, y: Int -> x + y }
val result = calculate(5, 3, addition) // Result: 8Code language: JavaScript (javascript)

In this example, the calculate function accepts two integers (a and b) and a function (operation) that takes two integers and returns an integer. The operation function can be any function that matches the specified signature.

The higher-order function allows flexibility by accepting different operations, such as addition, subtraction, multiplication, or even custom functions, to be passed as arguments.

Question: In the given Kotlin code, there is a bug preventing the loop from executing correctly. Identify the bug and provide a fix.

val numbers = mutableListOf(1, 2, 3, 4, 5)

for (i in numbers.indices) {
    if (i % 2 == 0) {
        numbers.removeAt(i)
    }
}

println(numbers) // Output: [2, 4]Code language: JavaScript (javascript)

Answer: The bug is due to modifying the numbers list while iterating over it using indices. When an element is removed from the list, the indices shift, leading to incorrect removal of elements.

To fix the bug, iterate in reverse order or use a while loop:

val numbers = mutableListOf(1, 2, 3, 4, 5)

var i = numbers.size - 1
while (i >= 0) {
    if (i % 2 == 0) {
        numbers.removeAt(i)
    }
    i--
}

println(numbers) // Output: [2, 4]Code language: JavaScript (javascript)

By iterating in reverse order or using a while loop, the removal of elements does not affect the subsequent indices.

Question: Explain the concept of extension functions in Kotlin and provide an example of their usage.

Answer:

Extension functions in Kotlin allow developers to add new functions to existing classes without modifying their source code. They provide a convenient way to extend the functionality of classes, including third-party or built-in classes, without inheritance.

Here’s an example of an extension function:

fun String.removeSpaces(): String {
    return this.replace(" ", "")
}

val text = "Hello World"
val result = text.removeSpaces() // Result: "HelloWorld"Code language: JavaScript (javascript)

In this example, the removeSpaces function is defined as an extension function for the String class. It removes spaces from a string by utilizing the replace function. The extension function can be called directly on any string object, providing a more concise and readable way to manipulate strings.

Question: Explain the concept of functional programming in Kotlin and its advantages. Provide examples of functional programming techniques in Kotlin.

Answer: Functional programming is a programming paradigm that emphasizes the use of pure functions, immutability, and higher-order functions. Kotlin provides support for functional programming, enabling developers to write concise, readable, and maintainable code.

Advantages of functional programming in Kotlin include:

  1. Readability and Expressiveness: Functional programming techniques, such as using higher-order functions and function composition, can lead to code that is easier to read and understand.
  2. Immutability: Functional programming promotes immutability, reducing the complexity of state management and making code more predictable and thread-safe.
  3. Avoidance of Side Effects: Pure functions, which produce the same output for the same inputs and have no side effects, make code more reliable, testable, and debuggable.
  4. Concurrency and Parallelism: Functional programming facilitates writing code that is amenable to parallel and concurrent execution, leveraging techniques like immutability and pure functions.

Here are some examples of functional programming techniques in Kotlin:

  • Higher-Order Functions: Functions that take other functions as parameters or return functions as results, allowing for behavior parameterization.
  • Lambda Expressions: Concise function literals that can be passed as arguments or stored in variables, enabling anonymous function definitions.
  • Immutable Data Structures: Using read-only collections (e.g., List, Set, Map) and data classes to ensure immutability and avoid unintended modifications.
  • Function Composition: Combining multiple functions to create a new function by chaining their invocations, facilitating modular and reusable code.

Functional programming in Kotlin provides a powerful set of tools and techniques to write elegant and maintainable code, particularly when solving problems that involve transformations, aggregations, or concurrency.