All topics

Kotlin interview questions

70 questions with answers. 181 open jobs in India ask for Kotlin.

  1. Explain: Crossinline keyword

    Crossinline keyword

    The crossinline marker is used to mark lambdas that mustn’t allow non-local returns, especially when such lambda is passed to another execution context such as a higher order function that is not inlined, a local object or a nested function. In other words, helps us enforce the control flow (return statement) of lambda functions passed as arguments in inline functions. Avoiding non-local control flow.

    Links

    https://kotlinlang.org/docs/reference/inline-functions.html
    https://medium.com/@tferreirap/kotlin-quick-look-at-inline-noinline-and-crossinline-e62e8833db1f
    https://android.jlelse.eu/inline-noinline-crossinline-what-do-they-mean-b13f48e113c2

    From Android Interview Questions (Apache 2.0)

  2. Explain: Default method in kotlin interface

    Default method in kotlin interface

    Before getting into Kotlin default method in interface ,lets go through the default interface mthod in Java which was introduced in Java 8 and @JvmDefault annotaion in Kotlin

    default interface in Java

    Why default method is introduced in Java 8

    • In a typical abstraction based design where an interface has one or more implementation if any new method is to be added to the interface then all the implementations will be forced to implement it.
    • default interface method is introduced to deal with this issue which allow us to add new methods to the interface that are automatically available to implementations. In this way backward compatibility is neatly preserved without having to refactor the implementers.
    • The most typical use of default methods in interfaces is to incrementally provide additional functionality to a given type without breaking down the implementing classes.

    @JvmDefault annotation in Kotlin

    • @JvmDefault is an annotation + compiler flag in Kotlin to enable using Java 8 default interface methods.

    • @JvmDefault was introduced in Kotlin 1.2 which will be deprecated in nfavor of generating all the method bodies in interfaces directly when the code is compiled in a special mode.

    A basic interface in Kotlin looks like following

     interface Car {  
        fun getNoOfWheels()  
    }
    

    The java equvalent of the above Kotlin code is as follows

    interface Car {  
        void getNoOfWheels();  
    }
    

    Now lets add default implementation to the Kotlin code

    interface Car {  
        fun getNoOfWheels() {}  
    }
    

    The java equivalent code will be as following

      interface Car {  
        void getNoOfWheels();  
        final class DefaultImpls {  
            public static void getNoOfWheels(Car instance) { }  
        }  
    }
    
    • DefaultImpls is a compiler-generated construct for holding default implementations.In this case - the default getNoOfWheels() implementation. It's implemented as a static method by the same name, return type, an instance parameter (this references in the function body are modified to refer to the instance parameter), and finally any other parameters.

    • This is how Kotlin supports default methods even on Java 6 or 7.

    • Now lets consider adding @JvmDefault by adding configuration -Xjvm-default=enable

      interface Car {  
            @JvmDefault fun getNoOfWheels() {}  
        }
      

    Now in bytecode, It will use the native default interface method support and no longer uses DefaultImpls.

    public interface Car {  
        @JvmDefault default void getNoOfWheels() { }  
    }
    

    If we use -Xjvm-default=compatibility, it will use both the native default support while also still generating the DefaultImpls API. This is important for backward binary compatibility.

    interface Car {  
        @JvmDefault default void getNoOfWheels() { }  
        final class DefaultImpls {  
            @JvmDefault public static void load(Car instance) {  
                instance.getNoOfWheels();  
            }  
        }  
    }
    

    From Android Interview Questions (Apache 2.0)

  3. Describe constructors invocation order

    Constructors invocation order

    Suppose we have next code:

    open class Parent {
        private val a = println("Parent.a")
        constructor(arg: String = "Default arg for parent") {
            println("Parent primary constructor")
            println("Parent arg value = $arg")
        }
        init {
            println("Parent.init")
        }
        private val b = println("Parent.b")
    }
    class Child: Parent {
        private val a = println("Child.a")
        init {
            println("Child.init 1")
        }
        constructor(arg: String = "Default arg for child"): super(arg) {
            println("Child primary constructor")
        }
        constructor(arg: Int): this(arg.toString()) {
            println("Child secondary constructor")
        }
        init {
            println("Child.init 2")
        }
    }
    

    What will be displayed in the console in the following cases:

    • Parent()
    • Parent("Value")
    • Child()
    • Child("Value")
    • Child(IntValue)

    Parent()

    Parent.a
    Parent.init
    Parent.b
    Parent primary constructor
    Parent arg value = Default arg for parent
    

    Parent(Value)

    Parent.a
    Parent.init
    Parent.b
    Parent primary constructor
    Parent arg value = Value
    

    Child()

    Parent.a
    Parent.init
    Parent.b
    Parent primary constructor
    Parent arg value = Default arg for child
    Child.a
    Child.init 1
    Child.init 2
    Child primary constructor
    

    Child(Value)

    Parent.a
    Parent.init
    Parent.b
    Parent primary constructor
    Parent arg value = Value
    Child.a
    Child.init 1
    Child.init 2
    Child primary constructor
    

    Child(IntValue)

    Parent.a
    Parent.init
    Parent.b
    Parent primary constructor
    Parent arg value = 2
    Child.a
    Child.init 1
    Child.init 2
    Child primary constructor
    Child secondary constructor
    

    Tips: Code in initializer blocks effectively becomes part of the primary constructor. Delegation to the primary constructor happens as the first statement of a secondary constructor, so the code in all initializer blocks and property initializers is executed before the body of the secondary constructor.

    Links

    Classes

    From Android Interview Questions (Apache 2.0)

  4. Describe nullability and null safety

    Describe nullability and null safety

    Nullability is the ability of a variable to hold a null value. When a variable contains null, an attempt to dereference the variable leads to a NullPointerException. There are many ways to write code in order to minimize the probability of receiving null pointer exceptions.

    Support for nullable types

    The most important difference between Kotlin's and Java's type systems is Kotlin's explicit support for nullable types. It is a way to indicate which variables can possibly hold a null value. If a variable can be null, it's not safe to call a method on the variable because this can cause a NullPointerException. Kotlin prohibits such calls at compile time and thereby prevents lots of possible exceptions. At runtime, objects of nullable types and objects of non-nullable types are treated the same: A nullable type isn't a wrapper for a non-nullable type. All checks are performed at compile time. That means there's almost no runtime overhead for working with nullable types in Kotlin.

    In Java, if you don't write null checks, methods may throw a NullPointerException:

    // Java
    int stringLength(String a) {
        return a.length();
    }
    void main() {
        stringLength(null); // Throws a `NullPointerException`
    }
    

    This call will have the following output:

    java.lang.NullPointerException: Cannot invoke "String.length()" because "a" is null
        at test.java.Nullability.stringLength(Nullability.java:8)
        at test.java.Nullability.main(Nullability.java:12)
        at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
        at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    

    In Kotlin, all regular types are non-nullable by default unless you explicitly mark them as nullable. If you don't expect a to be null, declare the stringLength() function as follows:

    // Kotlin
    fun stringLength(a: String) = a.length
    

    The parameter a has the String type, which in Kotlin means it must always contain a String instance and it cannot contain null. Nullable types in Kotlin are marked with a question mark ?, for example, String?. The situation with a NullPointerException at runtime is impossible if a is String because the compiler enforces the rule that all arguments of stringLength() not be null.

    An attempt to pass a null value to the stringLength(a: String) function will result in a compile-time error, "Null can not be a value of a non-null type String":

    If you want to use this function with any arguments, including null, use a question mark after the argument type String? and check inside the function body to ensure that the value of the argument is not null:

    // Kotlin
    fun stringLength(a: String?): Int = if (a != null) a.length else 0
    

    After the check is passed successfully, the compiler treats the variable as if it were of the non-nullable type String in the scope where the compiler performs the check.

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  5. What is the difference between fold and reduce in Kotlin?

    Reduce

    • reduce method transforms a given collection into a single result. It takes a lamda operator to combine a pair of elements into a accumulated value.
      It then traverses the collection from left to right and stepwise combines the accumulated value with the next element.

        val numbers: List<Int> = listOf(1, 2, 3);  
        val sum = numbers.reduce { acc, next -> next + acc }  `
      
    • reduce method will throw RuntimeException if its operated on an empty list.

    • Signature of reduce method
      inline fun <S, T:S> Iterable<T>.reduce(operation: (acc:S, T) -> S): S
      The function defines a generic type S and subtype T of S, Finally reduce returns one value of type S.

    • In the following example the sum would exceed the range of Int because of that the data type of result is changed to Long. So it will throw compile error(Type argument is not within its bounds)
      val sum: Long = numbers.reduce<Long, Int> { acc, next -> acc.toLong() + next.toLong() }

    • To fix the compile error we will have to change the Long type to Number as Number is superset of Int. So It doesnt solve the problem of changing the result type

    Fold

    To address the issues created by reduce we can use fold

     `val numbers: List<Int> = listOf(1, 2, 3)  
      val sum = numbers.fold(0, { acc, next -> next + acc })`  
    

    Here first argument is initial value if list is empty the inital value is returned.
    inline fun <T, R> Iterable<T>.fold(initial:R, (acc:R, T) -> R): R
    In contrast to reduce(), it specifies two arbitrary generic types T and R.

    • We can change the result type to Long in the following example

      val sum: Long = numbers.fold(0L, { acc, next -> acc + next.toLong() })

    • fold provides the ability to change the result type.

    From Android Interview Questions (Apache 2.0)

  6. Explain: Enum

    Enum in Kotlin

    An enum in Kotlin is a special type that represents a group of related constants. It allows you to define a fixed set of values for a variable. Enum constants are typically used to represent a closed set of options or choices.

    To define an enum in Kotlin, you use the enum class keyword, followed by the name of the enum and the list of constant values inside curly braces. For example:

    enum class Color {
        RED, GREEN, BLUE
    }
    

    In the above example, the Color enum has three constants: RED, GREEN, and BLUE.

    Enums in Kotlin can also have properties and methods, similar to classes. Each enum constant can have its own values for these properties. For example:

    enum class Color(val rgb: Int) {
        RED(0xFF0000),
        GREEN(0x00FF00),
        BLUE(0x0000FF)
        fun description(): String {
            return when (this) {
                RED -> "Red color"
                GREEN -> "Green color"
                BLUE -> "Blue color"
            }
        }
    }
    

    In the above example, the Color enum has an additional property rgb associated with each constant. It also has a method description() that provides a textual description of each color.

    To access the properties and methods of an enum constant, you simply use dot notation. For example:

    val redColor = Color.RED
    println(redColor.rgb)           // Output: 16711680
    println(redColor.description()) // Output: Red color
    

    Enums in Kotlin can be useful in various scenarios, such as representing days of the week, menu options, status codes, and more. They provide a type-safe and concise way to define a fixed set of values.

    From Android Interview Questions (Apache 2.0)

  7. Explain: Generics

    Generics

    Generic programming is a way of writing our code in a flexible manner like we would in a dynamically-typed language. At the same time, generics allow us to write code safely and with as few compile-time errors as possible.

    Using generics in Kotlin enables the developer to focus on creating reusable solutions, or templates, for a wider range of problems.

    Generic class

    Classes in Kotlin can have type parameters, just like in Java:

    class Box<T>(t: T) {
        var value = t
    }
    

    To create an instance of such a class, simply provide the type arguments:

    val box: Box<Int> = Box<Int>(1)
    

    But if the parameters can be inferred, for example, from the constructor arguments, you can omit the type arguments:

    val box = Box(1) // 1 has type Int, so the compiler figures out that it is Box<Int>
    

    Generic functions

    Classes aren't the only declarations that can have type parameters. Functions can, too. Type parameters are placed before the name of the function:

    fun <T> singletonList(item: T): List<T> {
        // ...
    }
    fun <T> T.basicToString(): String { // extension function
        // ...
    }
    

    To call a generic function, specify the type arguments at the call site after the name of the function:

    val l = singletonList<Int>(1)
    

    Type arguments can be omitted if they can be inferred from the context, so the following example works as well:

    val l = singletonList(1)
    

    Generic constraints

    The set of all possible types that can be substituted for a given type parameter may be restricted by generic constraints.

    Upper bounds

    The most common type of constraint is an upper bound, which corresponds to Java's extends keyword:

    fun <T : Comparable<T>> sort(list: List<T>) {  ... }
    

    The type specified after a colon is the upper bound, indicating that only a subtype of Comparable<T> can be substituted for T. For example:

    sort(listOf(1, 2, 3)) // OK. Int is a subtype of Comparable<Int>
    sort(listOf(HashMap<Int, String>())) // Error: HashMap<Int, String> is not a subtype of Comparable<HashMap<Int, String>>
    

    The default upper bound (if there was none specified) is Any?. Only one upper bound can be specified inside the angle brackets. If the same type parameter needs more than one upper bound, you need a separate where-clause:

    fun <T> copyWhenGreater(list: List<T>, threshold: T): List<String>
        where T : CharSequence,
              T : Comparable<T> {
        return list.filter { it > threshold }.map { it.toString() }
    }
    

    The passed type must satisfy all conditions of the where clause simultaneously. In the above example, the T type must implement both CharSequence and Comparable.

    Type erasure

    The type safety checks that Kotlin performs for generic declaration usages are done at compile time. At runtime, the instances of generic types do not hold any information about their actual type arguments. The type information is said to be erased. For example, the instances of Foo<Bar> and Foo<Baz?> are erased to just Foo<*>.

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  8. Explain: Inline keyword

    Inline keyword

    Inline functions

    Using higher-order functions imposes certain runtime penalties: each function is an object, and it captures a closure, i.e. those variables that are accessed in the body of the function. Memory allocations (both for function objects and classes) and virtual calls introduce runtime overhead.

    But it appears that in many cases this kind of overhead can be eliminated by inlining the lambda expressions. Inlining is basically requesting the compiler to copy the (inlined) code at the calling place.

    Consider the following case:

    lock(l) { foo() }

    Instead of creating a function object for the parameter and generating a call, the compiler could emit the following code:

    l.lock()
    try {
        foo()
    }
    finally {
        l.unlock()
    }
    

    To make the compiler do this, we need to mark the lock() function with the inline modifier:

    inline fun <T> lock(lock: Lock, body: () -> T): T { ... }

    The inline modifier affects both the function itself and the lambdas passed to it: all of those will be inlined into the call site.

    Let's look on one more example. Let's create file with one function:

    fun doubleAction(
      action1: () -> Unit,
      action2: () -> Unit
    ) {
      action1()
      action2()
    }
    

    and after this, let's create class InlineFunctionExample that will be use this function:

    class InlineFunctionExample {
      fun run() {
        doubleAction(
          { println("First function") },
          { println("Second function") }
        )
      }
    }
    

    After decompile code of class InlineFunctionExample we will see next:

    public final class InlineFunctionExample {
       public final void run() {
          InlineFunctionKt.doubleAction((Function0)null.INSTANCE, (Function0)null.INSTANCE);
       }
    }
    

    Sometimes kotlin decompiler works strange (this code will not create NullPointerException), but we should note for ourself that our two lambdas are now instances of Function0 object.

    After adding inline keyword to doubleAction function:

    inline fun doubleAction(
      action1: () -> Unit,
      action2: () -> Unit
    ) {
      action1()
      action2()
    }
    

    we will get next decompiled code:

    public final class InlineFunctionKt {
       public static final void doubleAction(@NotNull Function0 action1, @NotNull Function0 action2) {
          int $i$f$doubleAction = 0;
          Intrinsics.checkNotNullParameter(action1, "action1");
          Intrinsics.checkNotNullParameter(action2, "action2");
          action1.invoke();
          action2.invoke();
       }
    }
    

    as we can see there are no object creation here.

    Inlining may cause the generated code to grow; however, if we do it in a reasonable way (i.e. avoiding inlining large functions), it will pay off in performance, especially at "megamorphic" call-sites inside loops.

    Inline properties

    The inline modifier can be used on accessors of properties that don't have a backing field. You can annotate individual property accessors:

    val foo: Foo
        inline get() = Foo()
    var bar: Bar
        get() = ...
        inline set(v) { ... }
    

    You can also annotate an entire property, which marks both of its accessors as inline:

    inline var bar: Bar
        get() = ...
        set(v) { ... }
    

    At the call site, inline accessors are inlined as regular inline functions.

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  9. Explain: Kotlin collections

    Collection(Kotlin)

    Collection usually contains a number of objects of the same type. Objects in a collection are called elements or items. For example, all the students in a department form a collection that can be used to calculate their average age. The following collection types are relevant for Kotlin:

    • List is an ordered collection with access to elements by indices – integer numbers that reflect their position. Elements can occur more than once in a list.

    • Set is a collection of unique elements. It reflects the mathematical abstraction of set: a group of objects without repetitions.

    • Map (or dictionary) is a set of key-value pairs. Keys are unique, and each of them maps to exactly one value. The values can be duplicates. Maps are useful for storing logical connections between objects.

    Collection Types

    The Kotlin Standard Library provides implementations for basic collection types: sets, lists, and maps. A pair of interfaces represent each collection type:

    • A read-only interface that provides operations for accessing collection elements.The read-only collection types are covariant( collection types have the same subtyping relationship as the element types. If a Rectangle class inherits from Shape, you can use a List<Rectangle> anywhere the List<Shape> is required.)

    • A mutable interface that extends the corresponding read-only interface with write operations: adding, removing, and updating its elements.

    The mutable collections aren't covariant; otherwise, this would lead to runtime failures. If MutableList<Rectangle> was a subtype of MutableList<Shape>, you could insert other Shape inheritors (for example, Circle) into it, thus violating its Rectangle type argument.

    Below is a diagram of the Kotlin collection interfaces

    Links

    https://kotlinlang.org/docs/reference/collections-overview.html

    From Android Interview Questions (Apache 2.0)

  10. Explain: Scope functions

    Scope functions

    The Kotlin standard library contains several functions whose sole purpose is to execute a block of code within the context of an object. When you call such a function on an object with a lambda expression provided, it forms a temporary scope. In this scope, you can access the object without its name. Such functions are called scope functions. There are five of them: let, run, with, apply, and also.

    Here's a typical usage of a scope function:

    Person("Alice", 20, "Amsterdam").let {
        println(it)
        it.moveTo("London")
        it.incrementAge()
        println(it)
    }
    

    The scope functions do not introduce any new technical capabilities, but they can make your code more concise and readable.

    Due to the similar nature of scope functions, choosing the right one for your case can be a bit tricky. The choice mainly depends on your intent and the consistency of use in your project.

    Distinctions

    Because the scope functions are all quite similar in nature, it's important to understand the differences between them. There are two main differences between each scope function:

    • The way to refer to the context object
    • The return value.

    Context object: this or it

    Inside the lambda of a scope function, the context object is available by a short reference instead of its actual name. Each scope function uses one of two ways to access the context object: as a lambda receiver (this) or as a lambda argument (it)

    fun main() {
        val str = "Hello"
        // this
        str.run {
            println("The receiver string length: $length")
            //println("The receiver string length: ${this.length}") // does the same
        }
        // it
        str.let {
            println("The receiver string's length is ${it.length}")
        }
    }
    

    this. run, with, and apply refer to the context object as a lambda receiver - by keyword this. Hence, in their lambdas, the object is available as it would be in ordinary class functions. In most cases, you can omit this when accessing the members of the receiver object, making the code shorter. On the other hand, if this is omitted, it can be hard to distinguish between the receiver members and external objects or functions. So, having the context object as a receiver (this) is recommended for lambdas that mainly operate on the object members: call its functions or assign properties.

    it.In turn, let and also have the context object as a lambda argument. If the argument name is not specified, the object is accessed by the implicit default name it. it is shorter than this and expressions with it are usually easier for reading. However, when calling the object functions or properties you don't have the object available implicitly like this. Hence, having the context object as it is better when the object is mostly used as an argument in function calls. it is also better if you use multiple variables in the code block.

    Return value

    The scope functions differ by the result they return:

    • apply and also return the context object.
    • let, run, and with return the lambda result.

    The return value of apply and also is the context object itself. Hence, they can be included into call chains as side steps: you can continue chaining function calls on the same object after them.

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  11. Explain: Visibility modifiers

    Visibility modifiers

    Kotlin allows you to enforce symbol visibility via visibility modifiers, which can be placed on symbol declarations.

    There are four visibility modifiers in Kotlin: private, protected, internal and public.

    • public: declarations are visible everywhere.
    • private: means visible inside this class only (including all its members)
    • protected: means visible inside this class (including all its members) + visible in subclasses too
    • internal: modifier are visible everywhere in the same module.

    If you don't supply a visibility modifier, you get the default visibility level, which is public.

    Java vs Kotlin

    • In Java, the default modifier is package private, in Kotlin is public.
    • Java’s package private doesn’t have an equivalent in Kotlin, the closest is internal.
    • An Outer class does not see private members of its inner class in Kotlin.
    • If you override a protected member and do not specify the visibility explicitly, the overriding member will also have protected visibility. In Java the visibility is according to the modifier and the default is still public.

    Links

    https://kotlinlang.org/docs/tutorials/kotlin-for-py/visibility-modifiers.html
    https://kotlinlang.org/docs/reference/visibility-modifiers.html
    https://medium.com/mindorks/kotlin-for-android-developers-visibility-modifiers-8d8a3b84d298
    https://medium.com/@HugoMatilla/kotlin-basics-visibility-modifiers-public-internal-protected-and-private-c3bf972aee11

    From Android Interview Questions (Apache 2.0)

  12. What are coroutines?

    Coroutines

    A coroutine is a concurrency design pattern that you can use on Android to simplify code that executes asynchronously. Coroutines were added to Kotlin in version 1.3 and are based on established concepts from other languages.

    On Android, coroutines help to manage long-running tasks that might otherwise block the main thread and cause your app to become unresponsive.

    Coroutines offers many benefits over other asynchronous solutions, including the following:

    • Lightweight. You can run many coroutines on a single thread due to support for suspension, which doesn't block the thread where the coroutine is running. Suspending saves memory over blocking while supporting many concurrent operations.
    • Fewer memory leaks. Use structured concurrency to run operations within a scope.
    • Built-in cancellation support. Cancellation is propagated automatically through the running coroutine hierarchy.
    • Jetpack integration. Many Jetpack libraries include extensions that provide full coroutines support. Some libraries also provide their own coroutine scope that you can use for structured concurrency.

    Example:

    import kotlinx.coroutines.*
    fun main() {
        GlobalScope.launch { // launch a new coroutine in background and continue
            delay(1000L) // non-blocking delay for 1 second (default time unit is ms)
            println("World!") // print after delay
        }
        println("Hello,") // main thread continues while coroutine is delayed
        Thread.sleep(2000L) // block main thread for 2 seconds to keep JVM alive
    }
    Output:
    Hello,
    World!
    

    Essentially, coroutines are light-weight threads. They are launched with launch coroutine builder in a context of some CoroutineScope. Here we are launching a new coroutine in the GlobalScope, meaning that the lifetime of the new coroutine is limited only by the lifetime of the whole application.

    The global idea behind coroutines is that a function can suspend its execution at some point and resume later on. One of the benefits however of coroutines is that when it comes to the developer, writing non-blocking code is essentially the same as writing blocking code. The programming model in itself doesn't really change.

    Take for instance the following code:

    fun postItem(item: Item) {
        launch {
            val token = preparePost()
            val post = submitPost(token, item)
            processPost(post)
        }
    }
    suspend fun preparePost(): Token {
        // makes a request and suspends the coroutine
        return suspendCoroutine { /* ... */ } 
    }
    

    This code will launch a long-running operation without blocking the main thread. The preparePost is what's called a suspendable function, thus the keyword suspend prefixing it. What this means as stated above, is that the function will execute, pause execution and resume at some point in time.

    • The function signature remains exactly the same. The only difference is suspend being added to it. The return type however is the type we want to be returned.
    • The code is still written as if we were writing synchronous code, top-down, without the need of any special syntax, beyond the use of a function called launch which essentially kicks-off the coroutine
    • The programming model and APIs remain the same. We can continue to use loops, exception handling, etc. and there's no need to learn a complete set of new APIs
    • It is platform independent. Whether we targeting JVM, JavaScript or any other platform, the code we write is the same. Under the covers the compiler takes care of adapting it to each platform.

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  13. What do you know about Any, Nothing, Unit types?

    Any, Nothing, Unit

    Any the root of the Kotlin class hierarchy. Any is the super type of all non-nullable types. Any can't hold the null value, for holding null value you can use Any?. Kotlin compiler treats kotlin.Any and java.lang.Object as two different types, but at runtime they are represented with the same java.lang.Object class.

    Nothing has no instances. You can use Nothing to represent "a value that never exists": for example, if a function has the return type of Nothing, it means that it never returns (always throws an exception). Nothing implicity extend any object that exists.

    fun fail(message: String): Nothing {
        throw IllegalStateException(message)
    }
    val address = employee.address ?: fail("${employee.name} has no address defined")
    println(address)
    // > java.lang.IllegalStateException: John has no address defined
    

    Unit In Java if we want that a function does return nothing we use void, Unit is the equivalent in Kotlin.The main characteristics of Unit against Java’s void are:

    • Unit is a type and therefore can be used as a type argument.
    • Only one value of this type exists.
    • It is returned implicitly. No need of a return statement.

    Links

    https://itnext.io/kotlin-basics-types-any-unit-and-nothing-674cc858035
    https://proandroiddev.com/kotlins-nothing-type-946de7d464fb
    https://blog.kotlin-academy.com/kotlins-nothing-its-usefulness-in-generics-5076a6a457f7
    https://stackoverflow.com/questions/38761021/does-any-object
    https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-any/
    https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-nothing.html
    https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-unit/

    From Android Interview Questions (Apache 2.0)

  14. What do you know about Channels?

    Channels

    Deferred values provide a convenient way to transfer a single value between coroutines. Channels provide a way to transfer a stream of values. Channel is a non-blocking primitive for communication between a sender (via SendChannel) and a receiver (via ReceiveChannel).

    Channel basics

    A Channel is conceptually very similar to BlockingQueue. One key difference is that instead of a blocking put operation it has a suspending send, and instead of a blocking take operation it has a suspending receive.

    val channel = Channel<Int>()
    launch {
        // this might be heavy CPU-consuming computation or async logic, we'll just send five squares
        for (x in 1..5) channel.send(x * x)
    }
    // here we print five received integers:
    repeat(5) { println(channel.receive()) }
    println("Done!")
    

    The output of this code is:

    1
    4
    9
    16
    25
    Done!
    

    Closing and iteration over channels

    Unlike a queue, a channel can be closed to indicate that no more elements are coming. On the receiver side it is convenient to use a regular for loop to receive elements from the channel.

    Conceptually, a close is like sending a special close token to the channel. The iteration stops as soon as this close token is received, so there is a guarantee that all previously sent elements before the close are received:

    val channel = Channel<Int>()
    launch {
        for (x in 1..5) channel.send(x * x)
        channel.close() // we're done sending
    }
    // here we print received values using `for` loop (until the channel is closed)
    for (y in channel) println(y)
    println("Done!")
    

    Building channel producers

    The pattern where a coroutine is producing a sequence of elements is quite common. This is a part of producer-consumer pattern that is often found in concurrent code. You could abstract such a producer into a function that takes channel as its parameter, but this goes contrary to common sense that results must be returned from functions.

    There is a convenient coroutine builder named produce that makes it easy to do it right on producer side, and an extension function consumeEach, that replaces a for loop on the consumer side:

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  15. What do you know about Coroutine Job?

    Coroutine Job

    Conceptually, a Job is a cancellable thing with a lifecycle that culminates in its completion. For every coroutine that is created, a Job instance is returned to uniquely identify that coroutine and allow you to manage its lifecycle.

    The most basic instances of Job interface are created like this:

    • Coroutine job is created with launch coroutine builder. It runs a specified block of code and completes on completion of this block.
    • CompletableJob is created with a Job() factory function. It is completed by calling CompletableJob.complete.

    Jobs can be arranged into parent-child hierarchies where cancellation of a parent leads to immediate cancellation of all its children recursively. Failure of a child with an exception other than CancellationException immediately cancels its parent and, consequently, all its other children.

    Job states

    State isActive isCompleted isCancelled
    New (optional initial state) false false false
    Active (default initial state) true false false
    Completing (transient state) true false false
    Cancelling (transient state) false false true
    Cancelled (final state) false true true
    Completed (final state) false true false

    Usually, a job is created in the active state (it is created and started). However, coroutine builders that provide an optional start parameter create a coroutine in the new state when this parameter is set to CoroutineStart.LAZY. Such a job can be made active by invoking start or join.

    A job is active while the coroutine is working or until CompletableJob is completed, or until it fails or cancelled.

    Failure of an active job with an exception makes it cancelling. A job can be cancelled at any time with cancel function that forces it to transition to the cancelling state immediately. The job becomes cancelled when it finishes executing its work and all its children complete.

    Completion of an active coroutine's body or a call to CompletableJob.complete transitions the job to the completing state. It waits in the completing state for all its children to complete before transitioning to the completed state. Note that completing state is purely internal to the job. For an outside observer a completing job is still active, while internally it is waiting for its children.

                                              wait children
        +-----+ start  +--------+ complete   +-------------+  finish  +-----------+
        | New | -----> | Active | ---------> | Completing  | -------> | Completed |
        +-----+        +--------+            +-------------+          +-----------+
                         |  cancel / fail       |
                         |     +----------------+
                         |     |
                         V     V
                     +------------+                           finish  +-----------+
                     | Cancelling | --------------------------------> | Cancelled |
                     +------------+                                   +-----------+
    

    A Job instance in the coroutineContext represents the coroutine itself.

    Cancellation cause

    A coroutine job is said to complete exceptionally when its body throws an exception; a CompletableJob is completed exceptionally by calling CompletableJob.completeExceptionally. An exceptionally completed job is cancelled and the corresponding exception becomes the cancellation cause of the job.

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  16. What do you know about Flow?

    Flow

    In coroutines, a flow is a type that can emit multiple values sequentially, as opposed to suspend functions that return only a single value. For example, you can use a flow to receive live updates from a database.

    Flows are built on top of coroutines and can provide multiple values. A flow is conceptually a stream of data that can be computed asynchronously. To represent the stream of values that are being asynchronously computed, we can use a Flow<Int> type:

    fun simple(): Flow<Int> = flow { // flow builder
        for (i in 1..3) {
            delay(100) // pretend we are doing something useful here
            emit(i) // emit next value
        }
    }
    fun main() = runBlocking<Unit> {
        // Launch a concurrent coroutine to check if the main thread is blocked
        launch {
            for (k in 1..3) {
                println("I'm not blocked $k")
                delay(100)
            }
        }
        // Collect the flow
        simple().collect { value -> println(value) } 
    }
    

    This code waits 100ms before printing each number without blocking the main thread. This is verified by printing "I'm not blocked" every 100ms from a separate coroutine that is running in the main thread:

    I'm not blocked 1
    1
    I'm not blocked 2
    2
    I'm not blocked 3
    3
    

    A flow is very similar to an Iterator that produces a sequence of values, but it uses suspend functions to produce and consume values asynchronously. This means, for example, that the flow can safely make a network request to produce the next value without blocking the main thread.

    There are three entities involved in streams of data:

    • A producer produces data that is added to the stream. Thanks to coroutines, flows can also produce data asynchronously;
    • (Optional) Intermediaries can modify each value emitted into the stream or the stream itself;
    • A consumer consumes the values from the stream.

    In Android, a data source or repository is typically a producer of UI data that has the View as the consumer that ultimately displays the data. Other times, the View layer is a producer of user input events and other layers of the hierarchy consume them. Layers in between the producer and consumer usually act as intermediaries that modify the stream of data to adjust it to the requirements of the following layer.

    Flow builders

    There are the following basic ways to create a flow:

    • flowOf(…) functions to create a flow from a fixed set of values;
    • asFlow() extension functions on various types to convert them into flows;
    • flow { … } builder function to construct arbitrary flows from sequential calls to emit function;
    • channelFlow { … } builder function to construct arbitrary flows from potentially concurrent calls to the send function.
    • MutableStateFlow and MutableSharedFlow() define the corresponding constructor functions to create a hot flow that can be directly updated.

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  17. What do you know about JvmOverloads annotation?

    JvmOverloads annotation

    Instructs the Kotlin compiler to generate overloads for this function that substitute default parameter values.

    If a method has N parameters and M of which have default values, M overloads are generated: the first one takes N-1 parameters (all but the last one that takes a default value), the second takes N-2 parameters, and so on.

    Functions with parameters having a default value must use @JvmOverloads. Without this annotation it is impossible to invoke the Kotlin function using any default values from Java.

    When using @JvmOverloads, inspect the generated methods to ensure they each make sense. If they do not, perform one or both of the following refactorings until satisfied:

    • Change the parameter order to prefer those with defaults being towards the end.
    • Move the defaults into manual function overloads.

    Incorrect: No @JvmOverloads

    class Greeting {
        fun sayHello(prefix: String = "Mr.", name: String) {
            println("Hello, $prefix $name")
        }
    }
    
    public class JavaClass {
        public static void main(String... args) {
            Greeting greeting = new Greeting();
            greeting.sayHello("Mr.", "Bob");
        }
    }
    

    Correct: @JvmOverloads annotation.

    class Greeting {
        @JvmOverloads
        fun sayHello(prefix: String = "Mr.", name: String) {
            println("Hello, $prefix $name")
        }
    }
    
    public class JavaClass {
        public static void main(String... args) {
            Greeting greeting = new Greeting();
            greeting.sayHello("Bob");
        }
    }
    

    Links

    JvmOverloads
    Kotlin-Java interop guide

    From Android Interview Questions (Apache 2.0)

  18. What do you know about JvmStatic and JvmField annotations?

    JvmStatic and JvmField annotations

    JvmField

    If you need to expose a Kotlin property as a field in Java, annotate it with the @JvmField annotation. The field will have the same visibility as the underlying property. You can annotate a property with @JvmField if it:

    • has a backing field;
    • is not private;
    • does not have open, override or const modifiers;
    • is not a delegated property.
    class User(id: String) {
        @JvmField val ID = id
    }
    
    // Java
    class JavaClient {
        public String getID(User user) {
            return user.ID;
        }
    }
    

    Late-Initialized properties are also exposed as fields. The visibility of the field will be the same as the visibility of lateinit property setter.

    Kotlin properties declared in a named object or a companion object will have static backing fields either in that named object or in the class containing the companion object.

    Annotating such a property with @JvmField makes it a static field with the same visibility as the property itself.

    class Key(val value: Int) {
        companion object {
            @JvmField
            val COMPARATOR: Comparator<Key> = compareBy<Key> { it.value }
        }
    }
    
    // Java
    Key.COMPARATOR.compare(key1, key2);
    // public static final field in Key class
    

    JvmStatic

    Kotlin represents package-level functions as static methods. Kotlin can also generate static methods for functions defined in named objects or companion objects if you annotate those functions as @JvmStatic. If you use this annotation, the compiler will generate both a static method in the enclosing class of the object and an instance method in the object itself. For example:

    class C {
        companion object {
            @JvmStatic fun callStatic() {}
            fun callNonStatic() {}
        }
    }
    

    Now, callStatic() is static in Java while callNonStatic() is not:

    C.callStatic(); // works fine
    C.callNonStatic(); // error: not a static method
    C.Companion.callStatic(); // instance method remains
    C.Companion.callNonStatic(); // the only way it works
    

    Same for named objects:

    object Obj {
        @JvmStatic fun callStatic() {}
        fun callNonStatic() {}
    }
    

    In Java:

    Obj.callStatic(); // works fine
    Obj.callNonStatic(); // error
    Obj.INSTANCE.callNonStatic(); // works, a call through the singleton instance
    Obj.INSTANCE.callStatic(); // works too
    

    Starting from Kotlin 1.3, @JvmStatic applies to functions defined in companion objects of interfaces as well. Such functions compile to static methods in interfaces. Note that static method in interfaces were introduced in Java 1.8, so be sure to use the corresponding targets.

    interface ChatBot {
        companion object {
            @JvmStatic fun greet(username: String) {
                println("Hello, $username")
            }
        }
    }
    

    @JvmStatic annotation can also be applied on a property of an object or a companion object making its getter and setter methods static members in that object or the class containing the companion object.

    Links

    Calling Kotlin from Java

    From Android Interview Questions (Apache 2.0)

  19. What do you know about Rich Errors?

    Rich Errors

    Rich Errors is an upcoming Kotlin language feature that brings a new, type-safe way of handling errors. It allows developers to define functions that can return either a success value or a specific set of error types (e.g., NetworkError | TimeoutError). This approach removes the need for workarounds such as sealed classes or null-based error handling.

    The | operator represents a union type, meaning the function can return one of several possible types. In the context of Rich Errors, this allows combining a success type with a predefined set of error types directly in the return type, making all possible outcomes explicit at the API level: 1

    // Basic API with a union return
    fun fetchUser(id: UserId): User | NotFound | NetworkFailure
    // Suspending API with several domain errors
    suspend fun uploadAvatar(file: ImageFile): Url | UnsupportedFormat | QuotaExceeded | NetworkFailure
    // Propagating unions across layers
    fun loadProfile(id: UserId): Profile | NotFound | NetworkFailure | DecodeError
    

    At the call site, you handle the union with a when expression and smart‑casts:

    when (val r = fetchUser(currentId)) {
        is User -> showProfile(r)
        is NotFound -> showMissingUser()
        is NetworkFailure -> showOfflineMessage(r)
    }
    

    You can also map a union to UI state or another union, preserving exhaustiveness:

    fun toUi(result: AuthToken | InvalidCredentials | NetworkFailure): UiState = when (result) {
        is AuthToken -> UiState.Authenticated(result)
        is InvalidCredentials -> UiState.Error("Invalid email or password")
        is NetworkFailure -> UiState.Error("Check your connection and try again")
    }
    

    Motivation for Rich Errors

    Traditional exception-based error handling is powerful but has some drawbacks:2

    • Hidden control flow: exceptions don’t appear in function signatures;
    • Mixed concerns: thrown types are not always explicit or structured;
    • Composition friction: composing results across layers often requires try/catch;
    • Multiplatform nuances: mapping exceptions across different platforms can be uneven.

    Kotlin already offers Result<T> and functional helpers that address part of this. Rich errors extend the idea: make failure channels explicit, typed, and composable — while keeping excellent interop with existing code.3

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  20. What do you know about StateFlow and SharedFlow?

    StateFlow and SharedFlow

    StateFlow and SharedFlow are Flow APIs that enable flows to optimally emit state updates and emit values to multiple consumers.

    StateFlow

    StateFlow is a state-holder observable flow that emits the current and new state updates to its collectors. The current state value can also be read through its value property. To update state and send it to the flow, assign a new value to the value property of the MutableStateFlow class.

    In Android, StateFlow is a great fit for classes that need to maintain an observable mutable state.

    Following the examples from Kotlin flows, a StateFlow can be exposed from the LatestNewsViewModel so that the View can listen for UI state updates and inherently make the screen state survive configuration changes.

    class LatestNewsViewModel(
        private val newsRepository: NewsRepository
    ) : ViewModel() {
        // Backing property to avoid state updates from other classes
        private val _uiState = MutableStateFlow(LatestNewsUiState.Success(emptyList()))
        // The UI collects from this StateFlow to get its state updates
        val uiState: StateFlow<LatestNewsUiState> = _uiState
        init {
            viewModelScope.launch {
                newsRepository.favoriteLatestNews
                    // Update View with the latest favorite news
                    // Writes to the value property of MutableStateFlow,
                    // adding a new element to the flow and updating all
                    // of its collectors
                    .collect { favoriteNews ->
                        _uiState.value = LatestNewsUiState.Success(favoriteNews)
                    }
            }
        }
    }
    // Represents different states for the LatestNews screen
    sealed class LatestNewsUiState {
        data class Success(news: List<ArticleHeadline>): LatestNewsUiState()
        data class Error(exception: Throwable): LatestNewsUiState()
    }
    

    The class responsible for updating a MutableStateFlow is the producer, and all classes collecting from the StateFlow are the consumers. Unlike a cold flow built using the flow builder, a StateFlow is hot: collecting from the flow doesn't trigger any producer code. A StateFlow is always active and in memory, and it becomes eligible for garbage collection only when there are no other references to it from a garbage collection root.

    To convert any flow to a StateFlow, use the stateIn intermediate operator.

    StateFlow and LiveData have similarities. Both are observable data holder classes, and both follow a similar pattern when used in your app architecture.

    Note, however, that StateFlow and LiveData do behave differently:

    • StateFlow requires an initial state to be passed in to the constructor, while LiveData does not.
    • LiveData.observe() automatically unregisters the consumer when the view goes to the STOPPED state, whereas collecting from a StateFlow or any other flow does not.

    SharedFlow

    The shareIn function returns a SharedFlow, a hot flow that emits values to all consumers that collect from it. A SharedFlow is a highly-configurable generalization of StateFlow.

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  21. What do you know about companion object?

    сompanion object

    If you need to write a function that can be called without having a class instance but that needs access to the internals of a class (such as a factory method), you can declare a companion object inside your class and access its members using only the class name as a qualifier1:

    class MyClass {
        companion object {
            fun createInstance(): MyClass = MyClass()
        }
    }
    

    Now we can call the function createInstance() using only the class name:

    val instance = MyClass.createInstance()
    

    Named Companion Object

    By default, a companion object’s name is Companion. However, it is possible to rename it. Let’s implement a Factory Method design pattern in its simplest form. The Factory Method design pattern handles object creation. We’ll implement this design pattern using a companion object. Let’s name its companion object Factory:

    class MyClass {
        companion object Factory {
            fun createInstance(): MyClass = MyClass()
        }
    }
    

    Now, if we prefer to make use of the companion object by the dedicated name, simply place it after the class name:

    val instance = MyClass.Factory.createInstance()
    

    Why Use Companion Objects?

    Companion objects offer several benefits:

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  22. What do you know about data classes?

    data class

    A data class in Kotlin is a specialized class that is primarily designed to hold and represent data. It's a concise way to create classes that are focused on storing properties and providing common functionalities, without the need for boilerplate code.

    Kotlin data classes are particularly useful when you need to model simple, immutable data structures.1 For each data class, the compiler automatically generates additional member functions that allow you to print an instance to readable output, compare instances, copy instances, and more. Data classes are marked with data:2

    data class User(val name: String, val age: Int)
    

    The compiler automatically derives the following members from all properties declared in the primary constructor:

    • equals()/hashCode() pair;
    • toString() of the form "User(name=John, age=42)";
    • componentN() functions corresponding to the properties in their order of declaration;
    • copy() function.3

    Data classes may extend other classes and implement the interfaces, but also there are some limitations:

    • The primary constructor must have at least one parameter;
    • All primary constructor parameters must be marked as val or var;
    • Data classes can't be abstract, open, sealed, or inner.4

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  23. What do you know about data objects?

    Data objects

    When printing a plain object declaration in Kotlin, the string representation contains both its name and the hash of the object:

    object MyObject
    fun main() {
        println(MyObject) 
        // MyObject@hashcode
    }
    

    Output:

    MyObject@3941a79c
    

    However, by marking an object declaration with the data modifier, you can instruct the compiler to return the actual name of the object when calling toString(), the same way it works for data classes:

    data object MyDataObject {
        val number: Int = 3
    }
    fun main() {
        println(MyDataObject) 
        // MyDataObject
    }
    

    Output:

    MyDataObject
    

    Additionally, the compiler generates several functions for your data object:

    • toString() returns the name of the data object;
    • equals()/hashCode() enables equality checks and hash-based collections.

    Note: You can't provide a custom equals or hashCode implementation for a data object.

    The equals() function for a data object ensures that all objects that have the type of your data object are considered equal. In most cases, you will only have a single instance of your data object at runtime, since a data object declares a singleton. However, in the edge case where another object of the same type is generated at runtime (for example, by using platform reflection with java.lang.reflect or a JVM serialization library that uses this API under the hood), this ensures that the objects are treated as being equal.

    The generated hashCode() function has a behavior that is consistent with the equals() function, so that all runtime instances of a data object have the same hash code.

    Differences between data objects and data classes

    While data object and data class declarations are often used together and have some similarities, there are some functions that are not generated for a data object:

    • No copy() function. Because a data object declaration is intended to be used as singletons, no copy() function is generated. Singletons restrict the instantiation of a class to a single instance, which would be violated by allowing copies of the instance to be created;
    • No componentN() function. Unlike a data class, a data object does not have any data properties. Since attempting to destructure such an object without data properties wouldn't make sense, no componentN() functions are generated.

    Use data objects with sealed hierarchies

    Data object declarations are particularly useful for sealed hierarchies like sealed classes or sealed interfaces. They allow you to maintain symmetry with any data classes you may have defined alongside the object.

    In this example, declaring EndOfFile as a data object instead of a plain object means that it will get the toString() function without the need to override it manually:

    sealed interface ReadResult
    data class Number(val number: Int) : ReadResult
    data class Text(val text: String) : ReadResult
    data object EndOfFile : ReadResult
    fun main() {
        println(Number(7)) 
        // Number(number=7)
        println(EndOfFile) 
        // EndOfFile
    }
    

    Links

    Data objects

    From Android Interview Questions (Apache 2.0)

  24. What do you know about delegated properties?

    Delegated properties

    There are certain common kinds of properties, that, though you can implement them manually every time you need them, it would be helpful to implement them once and add to a library. Examples include:

    • Lazy properties: the value gets computed only upon first access;
    • Observable properties: listeners get notified about changes to this property;
    • Storing properties in a map, instead of a separate field for each property.

    To cover these (and other) cases, Kotlin supports delegated properties:

    class Example {
        var p: String by Delegate()
    }
    

    The syntax is: val/var <property name>: <Type> by <expression>. The expression after by is a delegate, because get() (and set()) corresponding to the property will be delegated to its getValue() and setValue() methods. Property delegates don’t have to implement any interface, but they have to provide a getValue() function (and setValue() --- for var s).

    For example:

    import kotlin.reflect.KProperty
    class Delegate {
        operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
            return "$thisRef, thank you for delegating '${property.name}' to me!"
        }
        operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
            println("$value has been assigned to '${property.name}' in $thisRef.")
        }
    }
    

    When you read from p that delegates to an instance of Delegate, the getValue() function from Delegate is called, so that its first parameter is the object you read p from and the second parameter holds a description of p itself (for example, you can take its name).

    val e = Example()
    println(e.p)
    

    This prints:

    Example@33a17727, thank you for delegating ‘p’ to me!
    

    Similarly, when you assign to p, the setValue() function is called. The first two parameters are the same, and the third holds the value being assigned:

    e.p = "NEW"
    

    This prints:

    NEW has been assigned to ‘p’ in Example@33a17727.
    

    Standard delegates

    The Kotlin standard library provides factory methods for several useful kinds of delegates.

    Lazy properties

    lazy() is a function that takes a lambda and returns an instance of Lazy<T> which can serve as a delegate for implementing a lazy property: the first call to get() executes the lambda passed to lazy() and remembers the result, subsequent calls to get() simply return the remembered result.

    val lazyValue: String by lazy {
        println("computed!")
        "Hello"
    }
    fun main() {
        println(lazyValue)
        println(lazyValue)
    }
    

    By default, the evaluation of lazy properties is synchronized: the value is computed only in one thread, and all threads will see the same value. If the synchronization of initialization delegate is not required, so that multiple threads can execute it simultaneously, pass LazyThreadSafetyMode.PUBLICATION as a parameter to the lazy() function.

    And if you're sure that the initialization will always happen on the same thread as the one where you use the property, you can use LazyThreadSafetyMode.NONE: it doesn't incur any thread-safety guarantees and the related overhead.

    Observable properties

    Delegates.observable() takes two arguments: the initial value and a handler for modifications.

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  25. What do you know about extensions?

    Extensions

    Kotlin provides the ability to extend a class or an interface with new functionality without having to inherit from the class or use design patterns such as Decorator. This is done via special declarations called extensions.

    For example, you can write new functions for a class or an interface from a third-party library that you can't modify. Such functions can be called in the usual way, as if they were methods of the original class. This mechanism is called an extension function. There are also extension properties that let you define new properties for existing classes.

    Extension functions

    To declare an extension function, prefix its name with a receiver type, which refers to the type being extended. The following adds a swap function to MutableList<Int>:

    fun MutableList<Int>.swap(index1: Int, index2: Int) {
        val tmp = this[index1] // 'this' corresponds to the list
        this[index1] = this[index2]
        this[index2] = tmp
    }
    

    The this keyword inside an extension function corresponds to the receiver object (the one that is passed before the dot). Now, you can call such a function on any MutableList<Int>:

    val list = mutableListOf(1, 2, 3)
    list.swap(0, 2) // 'this' inside 'swap()' will hold the value of 'list'
    

    This function makes sense for any MutableList<T>, and you can make it generic:

    fun <T> MutableList<T>.swap(index1: Int, index2: Int) {
        val tmp = this[index1] // 'this' corresponds to the list
        this[index1] = this[index2]
        this[index2] = tmp
    }
    

    You need to declare the generic type parameter before the function name to make it available in the receiver type expression.

    Extension properties

    Kotlin supports extension properties much like it supports functions:

    val <T> List<T>.lastIndex: Int
        get() = size - 1
    

    Note. Since extensions do not actually insert members into classes, there's no efficient way for an extension property to have a backing field. This is why initializers are not allowed for extension properties. Their behavior can only be defined by explicitly providing getters/setters.

    Example:

    val House.number = 1 // error: initializers are not allowed for extension properties
    

    Nullable receiver

    Note that extensions can be defined with a nullable receiver type. These extensions can be called on an object variable even if its value is null, and they can check for this == null inside the body.

    This way, you can call toString() in Kotlin without checking for null, as the check happens inside the extension function:

    fun Any?.toString(): String {
        if (this == null) return "null"
        // after the null check, 'this' is autocast to a non-null type, so the toString() below
        // resolves to the member function of the Any class
        return toString()
    }
    

    Extensions are resolved statically

    Extensions do not actually modify the classes they extend. By defining an extension, you are not inserting new members into a class, only making new functions callable with the dot-notation on variables of this type.

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  26. What do you know about functional interfaces?

    Functional (SAM) interfaces

    An interface with only one abstract method is called a functional interface, or a Single Abstract Method (SAM) interface. The functional interface can have several non-abstract members but only one abstract member.

    To declare a functional interface in Kotlin, use the fun modifier.1

    fun interface KRunnable {
       fun invoke()
    }
    

    SAM conversions

    For functional interfaces, you can use SAM conversions that help make your code more concise and readable by using lambda expressions.

    Instead of creating a class that implements a functional interface manually, you can use a lambda expression. With a SAM conversion, Kotlin can convert any lambda expression whose signature matches the signature of the interface's single method into the code, which dynamically instantiates the interface implementation.

    For example, consider the following Kotlin functional interface:

    fun interface IntPredicate {
       fun accept(i: Int): Boolean
    }
    

    If you don't use a SAM conversion, you will need to write code like this:

    // Creating an instance of a class
    val isEven = object : IntPredicate {
       override fun accept(i: Int): Boolean {
           return i % 2 == 0
       }
    }
    

    By leveraging Kotlin's SAM conversion, you can write the following equivalent code instead:

    // Creating an instance using lambda
    val isEven = IntPredicate { it % 2 == 0 }
    

    A short lambda expression replaces all the unnecessary code:

    fun interface IntPredicate {
       fun accept(i: Int): Boolean
    }
    val isEven = IntPredicate { it % 2 == 0 }
    fun main() {
       println("Is 7 even? - ${isEven.accept(7)}")
    }
    

    @FunctionalInterface annotation

    @FunctionalInterface Annotation:

    • This annotation is not mandatory but helps indicate that an interface is intended to be a functional interface;
    • It provides compile-time checking to ensure the interface adheres to the single abstract method constraint.2

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  27. What do you know about guard conditions?

    Guard conditions

    Guard conditions allow you to include more than one condition to the branches of a when expression or statement, making complex control flow more explicit and concise. You can use guard conditions with when as long as it has a subject.1

    Place a guard condition after the primary condition in the same branch, separated by if:2

    fun feedAnimal(animal: Animal) {
        when (animal) {
            // Branch with only primary condition
            // Calls feedDog() when animal is Dog
            is Animal.Dog -> feedDog()
            // Branch with both primary and guard conditions
            // Calls feedCat() when animal is Cat and not mouseHunter
            is Animal.Cat if !animal.mouseHunter -> feedCat()
            // Prints "Unknown animal" if none of the above conditions match
            else -> println("Unknown animal")
        }
    }
    fun main() {
        val animals = listOf(
            Animal.Dog("Beagle"),
            Animal.Cat(mouseHunter = false),
            Animal.Cat(mouseHunter = true)
        )
        animals.forEach { feedAnimal(it) }
        // Feeding a dog
        // Feeding a cat
        // Unknown animal
    }
    

    You can't use guard conditions when you have multiple conditions separated by a comma. For example:

    0, 1 -> print("x == 0 or x == 1")
    

    In a single when expression or statement, you can combine branches with and without guard conditions. The code in a branch with a guard condition runs only if both the primary condition and the guard condition evaluate to true. If the primary condition doesn't match, the guard condition isn't evaluated.

    Since when statements don't need to cover all cases, using guard conditions in when statements without an else branch means that if no conditions match, no code is run.3

    Guard conditions also support else if:4

    when (animal) {
        // Checks if `animal` is `Dog`
        is Animal.Dog -> feedDog()
        // Guard condition that checks if `animal` is `Cat` and not `mouseHunter`
        is Animal.Cat if !animal.mouseHunter -> feedCat()
        // Calls giveLettuce() if none of the above conditions match and animal.eatsPlants is true
        else if animal.eatsPlants -> giveLettuce()
        // Prints "Unknown animal" if none of the above conditions match
        else -> println("Unknown animal")
    }
    

    Android example

    Guard conditions can be especially useful when working with UI states, sealed classes, or other scenarios where multiple branches share the same type but require additional validation.

    A common example is handling a successful state differently depending on whether the received data is empty or not.

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  28. What do you know about lambda expressions?

    Lambda expressions

    A lambda expression in Kotlin is essentially an anonymous function (a function without a name) that can be treated as a value — meaning it can be assigned to variables, passed as parameters, or returned from other functions.1 The following snippet demonstrates the use of two different lambdas in variable assignment expressions:

    val lambda1 = { println("Hello Lambdas") }
    val lambda2 : (String) -> Unit = { name: String -> 
        println("My name is $name") 
    }
    

    For both of these cases, everything to the right-hand side of the equals sign is the lambda.2

    Syntax

    Lambda expressions in Kotlin are defined using the following syntax:

    val lambdaName: Type = { argumentList -> codeBody }
    
    • val. This keyword declares an immutable variable (value) in Kotlin;
    • lambdaName. This is the name you assign to the variable that will store the lambda function;
    • Type. This indicates the type of the variable lambdaName. In the context of lambda expressions, the type usually specifies the expected parameter types and the return type of the lambda. For example, (Int, Int) -> Int signifies a lambda that takes two Int parameters and returns an Int;
    • argumentList. This section lists the parameters that the lambda function accepts. It could be one or more parameters, depending on the function's needs. These parameters are used in the codeBody to perform computations or operations;
    • codeBody. The codeBody is the heart of the lambda expression. It contains the code that defines the behavior of the lambda function. It can be a single expression or a block of statements enclosed in curly braces. The result of the last expression (or explicitly returned expression) within the codeBody becomes the return value of the lambda function.

    Example:

    val add: (Int, Int) -> Int = { a, b -> a + b }
    
    • lambdaName is add;
    • Type is (Int, Int) -> Int, indicating a lambda that takes two Int parameters and returns an Int;
    • argumentList is (a, b);
    • codeBody is a + b, which calculates the sum of the two parameters.

    Invoking a lambda expression

    Once you’ve defined a lambda expression, how can you invoke the function to actually run the code defined in the lambda body?

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  29. What do you know about lateinit?

    lateinit

    lateinit is a keyword used to define a property that will be initialized later. Unlike other properties declared with var, lateinit properties are not initialized at the time of object creation. This makes it particularly useful when the initial value of the property is not known at the time of declaration.1

    Example of lateinit usage:

    public class MyTest {
        lateinit var subject: TestSubject
        @SetUp fun setup() {
            subject = TestSubject()
        }
        @Test fun test() {
            subject.method()  // dereference directly
        }
    }
    

    Key features of lateinit modifier

    • Avoid Null Checks: lateinit allows you to avoid cumbersome null checks when working with nullable types. The lateinit keyword tells the compiler that you will ensure the property is initialized before usage;
    • No Initial Value Required: When using lateinit, you don't need to provide an initial value when the property is declared. This is particularly useful for properties that are not immediately initialized, such as UI components in Android;
    • Easily Set Up Late Initialized Properties: The lateinit modifier simplifies initializing properties in setup methods, unit tests, or other methods where the property can be assigned values dynamically.

    Key restrictions

    • Сan only be used with mutable properties (variables declared with the var keyword), cause read-only properties (declared with the val keyword) represent immutable values that must be initialized at the time of declaration;
    • Can be used only for non-primitive types (Int, Double, Float etc not allowed);
    • Cannot be used with nullable types, as it is designed to avoid dealing with null values;

    Checking whether a lateinit var is initialized

    To check whether a lateinit var has already been initialized, use .isInitialized on the reference to that property:

    if (foo::bar.isInitialized) {
        println(foo.bar)
    }
    

    This check is only available for properties that are lexically accessible when declared in the same type, in one of the outer types, or at top level in the same file.

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  30. What do you know about object keyword?

    object keyword

    The object keyword allow you to define a class and create an instance of it in a single step. This is useful when you need either a reusable singleton instance or a one-time object. Kotlin provides two key approaches for the object keyword:

    • object declarations for creating singletons;
    • object expressions for creating anonymous, one-time objects.1

    Object declarations

    You can create single instances of objects in Kotlin using object declarations, which always have a name following the object keyword. This allows you to define a class and create an instance of it in a single step, which is useful for implementing singletons:

    // Declares a Singleton object to manage data providers
    object DataProviderManager {
        private val providers = mutableListOf<DataProvider>()
        // Registers a new data provider
        fun registerDataProvider(provider: DataProvider) {
            providers.add(provider)
        }
        // Retrieves all registered data providers
        val allDataProviders: Collection<DataProvider> 
            get() = providers
    }
    

    To refer to the object, use its name directly:

    DataProviderManager.registerDataProvider(exampleProvider)
    

    Object declarations can also have supertypes, similar to how anonymous objects can inherit from existing classes or implement interfaces:

    object DefaultListener : MouseAdapter() {
        override fun mouseClicked(e: MouseEvent) { ... }
        override fun mouseEntered(e: MouseEvent) { ... }
    }
    

    Like variable declarations, object declarations are not expressions, so they cannot be used on the right-hand side of an assignment statement:

    // Syntax error: An object expression cannot bind a name.
    val myObject = object MySingleton {
    val name = "Singleton"
    }
    

    Object declarations cannot be local, which means they cannot be nested directly inside a function. However, they can be nested within other object declarations or non-inner classes.

    Note: The initialization of an object declaration is thread-safe and done on first access.

    Object expressions

    Object expressions declare a class and create an instance of that class, but without naming either of them. These classes are useful for one-time use. They can either be created from scratch, inherit from existing classes, or implement interfaces. Instances of these classes are also called anonymous objects because they are defined by an expression, not a name.

    Create anonymous objects from scratch

    Object expressions start with the object keyword.

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

Related topics

Where these questions come from

Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.