Skip to content

πŸ”΄ Kotlin Interview Questions and Answered to prepare for your next Android developer interview

Notifications You must be signed in to change notification settings

aershov24/kotlin-interview-questions

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

7 Commits
Β 
Β 

Repository files navigation

Kotlin Interview Questions and Answers from FullStack.Cafe

Kotlin is immensely practical. It addresses the problems that developers have, and not some guys in the academia. So, it has type inference, it has amazing type safety, good collection library, and concurrency library to top it. And it's now official - a lot of organisations are migrating their backend applications to Kotlin, and this trend is not likely to end soon. Follow along to check the most complete and comprehensive collection of the most common and advanced Kotlin Interview Questions every Android developer should know in 2020.

You could also find all the answers here πŸ‘‰ https://www.fullstack.cafe/Kotlin.

Q1: How to initialize an array in Kotlin with values? ⭐⭐

Questions Details:

In Java an array can be initialized such as:

 int numbers[] = new int[] {10, 20, 30, 40, 50}

How does Kotlin's array initialization look like?

Answer:

val numbers: IntArray = intArrayOf(10, 20, 30, 40, 50)

πŸ”— Source: stackoverflow.com

Q2: How to correctly concatenate a String in Kotlin? ⭐⭐

Answer:

In Kotlin, you can concatenate

  1. using string interpolation / templates
val a = "Hello"
val b = "World"
val c = "$a $b"
  1. using the + / plus() operator
val a = "Hello"
val b = "World" 
val c = a + b   // same as calling operator function a.plus(b)
val c = a.plus(b)

print(c)
  1. using the StringBuilder
val a = "Hello"
val b = "World"

val sb = StringBuilder()
sb.append(a).append(b)
val c = sb.toString()

print(c)

πŸ”— Source: stackoverflow.com

Q3: What is basic difference between fold and reduce in Kotlin? When to use which? ⭐⭐

Answer:

  • fold takes an initial value, and the first invocation of the lambda you pass to it will receive that initial value and the first element of the collection as parameters.
listOf(1, 2, 3).fold(0) { sum, element -> sum + element }

The first call to the lambda will be with parameters 0 and 1.

Having the ability to pass in an initial value is useful if you have to provide some sort of default value or parameter for your operation.

  • reduce doesn't take an initial value, but instead starts with the first element of the collection as the accumulator (called sum in the following example)
listOf(1, 2, 3).reduce { sum, element -> sum + element }

The first call to the lambda here will be with parameters 1 and 2.

πŸ”— Source: stackoverflow.com

Q4: What is the idiomatic way to remove duplicate strings from array? ⭐⭐

Questions Details:

How to remove duplicates from an Array<String?> in Kotlin?

Answer:

Use the distinct extension function:

val a = arrayOf("a", "a", "b", "c", "c")
val b = a.distinct() // ["a", "b", "c"]

You can also use:

  • toSet, toMutableSet
  • toHashSet - if you don't need the original ordering to be preserved

These functions produce a Set instead of a List and should be a little bit more efficient than distinct.

πŸ”— Source: stackoverflow.com

Q5: What is the difference between var and val in Kotlin? ⭐⭐

Answer:

  • var is like general variable and it's known as a mutable variable in kotlin and can be assigned multiple times.

  • val is like Final variable and it's known as immutable in Kotlin and can be initialized only single time.

+----------------+-----------------------------+---------------------------+
|                |             val             |            var            |
+----------------+-----------------------------+---------------------------+
| Reference type | Immutable(once initialized  | Mutable(can able to change|
|                | can't be reassigned)        | value)                    |
+----------------+-----------------------------+---------------------------+
| Example        | val n = 20                  | var n = 20                |
+----------------+-----------------------------+---------------------------+
| In Java        | final int n = 20;           | int n = 20;               |
+----------------+-----------------------------+---------------------------+

πŸ”— Source: stackoverflow.com

Q6: Where should I use var and where val? ⭐⭐

Answer:

Use var where value is changing frequently. For example while getting location of android device:

var integerVariable : Int? = null

Use val where there is no change in value in whole class. For example you want set textview or button's text programmatically.

val stringVariables : String = "Button's Constant or final Text"

πŸ”— Source: stackoverflow.com

Q7: What is a data class in Kotlin? ⭐⭐

Answer:

We frequently create classes whose main purpose is to hold data. In Kotlin, this is called a data class and is marked as data:

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

To ensure consistency and meaningful behavior of the generated code, data classes have to fulfill the following requirements:

  • The primary constructor needs to have at least one parameter;
  • All primary constructor parameters need to be marked as val or var;
  • Data classes cannot be abstract, open, sealed or inner;

πŸ”— Source: kotlinlang.org

Q8: What is a primary constructor in Kotlin? ⭐⭐

Answer:

The primary constructor is part of the class header. Unlike Java, you don't need to declare a constructor in the body of the class. Here's an example:

class Person(val firstName: String, var age: Int) {
    // class body
}

The main idea is by removing the constructor keyword, our code gets simplified and easy to understand.

πŸ”— Source: www.programiz.com

Q9: How to create singleton in Kotlin? ⭐⭐

Answer:

Just use object.

object SomeSingleton

The above Kotlin object will be compiled to the following equivalent Java code:

public final class SomeSingleton {
   public static final SomeSingleton INSTANCE;

   private SomeSingleton() {
      INSTANCE = (SomeSingleton)this;
      System.out.println("init complete");
   }

   static {
      new SomeSingleton();
   }
}

This is the preferred way to implement singletons on a JVM because it enables thread-safe lazy initialization without having to rely on a locking algorithm like the complex double-checked locking.

πŸ”— Source: medium.com

Q10: What will be result of the following code execution? ⭐⭐⭐

Questions Details:

What will be the output?

val aVar by lazy {
    println("I am computing this value")
    "Hola"
}
fun main(args: Array<String>) {
    println(aVar)
    println(aVar)
}

See πŸ‘‰ Answer

Q11: Explain lazy initialization in Kotlin ⭐⭐⭐

See πŸ‘‰ Answer

Q12: Explain the Null safety in Kotlin ⭐⭐⭐

See πŸ‘‰ Answer

Q13: Explain what is wrong with that code? ⭐⭐⭐

Questions Details:

Why is this code wrong?

class Student (var name: String) {
    init() {
        println("Student has got a name as $name")
    }

    constructor(sectionName: String, var id: Int) this(sectionName) {
    }
}

See πŸ‘‰ Answer

Q14: How are extensions resolved in Kotlin and what doest it mean? ⭐⭐⭐

See πŸ‘‰ Answer

Q15: What is a purpose of Companion Objects in Kotlin? ⭐⭐⭐

See πŸ‘‰ Answer

Q16: What is Lateinit in Kotlin and when would you use it? ⭐⭐⭐

See πŸ‘‰ Answer

Q17: When to use lateinit over lazy initialization in Kotlin? ⭐⭐⭐

See πŸ‘‰ Answer

Q18: May you briefly compare Kotlin vs Java? ⭐⭐⭐

See πŸ‘‰ Answer

Q19: What are coroutines in Kotlin? ⭐⭐⭐

See πŸ‘‰ Answer

Q20: What is the difference between suspending vs. blocking? ⭐⭐⭐

See πŸ‘‰ Answer

Q21: What is suspending function in Kotlin? ⭐⭐⭐

See πŸ‘‰ Answer

Q22: What is the equivalent of Java static methods in Kotlin? ⭐⭐⭐

See πŸ‘‰ Answer

Q23: Explain advantages of "when" vs "switch" in Kotlin ⭐⭐⭐

See πŸ‘‰ Answer

Q24: What are the advantages of Kotlin over Java? ⭐⭐⭐

See πŸ‘‰ Answer

Q25: What are some disadvantages of Kotlin? ⭐⭐⭐

See πŸ‘‰ Answer

Q26: What is the difference between "open" and "public" in Kotlin? ⭐⭐⭐

See πŸ‘‰ Answer

Q27: What is the difference between β€œconst” and β€œval”? ⭐⭐⭐

See πŸ‘‰ Answer

Q28: How to convert List to Map in Kotlin? ⭐⭐⭐

See πŸ‘‰ Answer

Q29: val mutableList vs var immutableList. When to use which in Kotlin? ⭐⭐⭐

See πŸ‘‰ Answer

Q30: What is the difference between List and Array types? ⭐⭐⭐

See πŸ‘‰ Answer

Q31: What is the idiomatic way to deal with nullable values, referencing or converting them? ⭐⭐⭐

Questions Details:

If I have a nullable type Xyz?, I want to reference it or convert it to a non-nullable type Xyz. What is the idiomatic way of doing so in Kotlin?

See πŸ‘‰ Answer

Q32: When would you use Elvis operator in Kotlin? ⭐⭐⭐

See πŸ‘‰ Answer

Q33: Rewrite this code in Kotlin ⭐⭐⭐

Questions Details:

Can you rewrite this Java code in Kotlin?

public class Singleton {
    private static Singleton instance = null;
    private Singleton(){
    }
    private synchronized static void createInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
    }
    public static Singleton getInstance() {
        if (instance == null) createInstance();
        return instance;
    }

See πŸ‘‰ Answer

Q34: What is a difference between a class and object in Kotlin? ⭐⭐⭐

See πŸ‘‰ Answer

Q35: How is it recommended to create constants in Kotlin? ⭐⭐⭐

See πŸ‘‰ Answer

Q36: May you use IntArray and an Array is in Kotlin interchangeably? ⭐⭐⭐

See πŸ‘‰ Answer

Q37: How would you create a singleton with parameter in Kotlin? ⭐⭐⭐

See πŸ‘‰ Answer

Q38: What is the Kotlin double-bang (!!) operator? ⭐⭐⭐

See πŸ‘‰ Answer

Q39: What is the purpose of Unit-returning in functions? Why is VALUE there? What is this VALUE? ⭐⭐⭐

Questions Details:

Explain what is the purpose of Unit-returning in functions? Why is VALUE there? What is this VALUE?

fun printHello(name : String?) : Unit { 
   if (name != null) 
     print("Hello, $name!") 
   else 
     print("Hi there!") 
   // We don't need to write 'return Unit.VALUE' or 'return', although we could 
}

See πŸ‘‰ Answer

Q40: What are scope functions in Kotlin? ⭐⭐⭐

See πŸ‘‰ Answer

Q41: Why would you use apply in Kotlin? ⭐⭐⭐

See πŸ‘‰ Answer

Q42: How would you refactor this code using "apply"? ⭐⭐⭐

Questions Details:

Consider:

class Message(message: String, signature: String) {
  val body = MessageBody()
  
  init {
    body.text = message + "\n" + signature
  }
}

Do you see any refactoring that could be done?

See πŸ‘‰ Answer

Q43: Why is there no static keyword in Kotlin? ⭐⭐⭐⭐

See πŸ‘‰ Answer

Q44: What is inline class in Kotlin and when do we need one? Provide an example. ⭐⭐⭐⭐

See πŸ‘‰ Answer

Q45: Provide a real use case when inline classes may be useful ⭐⭐⭐⭐

See πŸ‘‰ Answer

Q46: What is Coroutine Scope and how is that different from Coroutine Context? ⭐⭐⭐⭐

See πŸ‘‰ Answer

Q47: Explain the difference between Inline classes vs type aliases ⭐⭐⭐⭐

See πŸ‘‰ Answer

Q48: How would you override default getter for Kotlin data class? ⭐⭐⭐⭐

Questions Details:

Given the following Kotlin class:

data class Test(val value: Int)

How would I override the Int getter so that it returns 0 if the value negative?

See πŸ‘‰ Answer

Q49: How can I create β€œstatic” method for enum in Kotiln? ⭐⭐⭐⭐

See πŸ‘‰ Answer

Q50: How to create an instance of anonymous class of abstract class in Kotlin? ⭐⭐⭐⭐

Questions Details:

Assume that KeyAdapter is an abstract class with several methods that can be overridden.

In java I can do:

KeyListener keyListener = new KeyAdapter() {
    @Override public void keyPressed(KeyEvent keyEvent) {
        // ...
    }
};

How to do the same in Kotlin?

See πŸ‘‰ Answer

Q51: How to create empty constructor for data class in Kotlin? ⭐⭐⭐⭐

See πŸ‘‰ Answer

Q52: What are Object expressions in Kotlin and when to use them? ⭐⭐⭐⭐

See πŸ‘‰ Answer

Q53: What is Kotlin backing field is used for? ⭐⭐⭐⭐

See πŸ‘‰ Answer

Q54: Rewrite this code using "run" extension function ⭐⭐⭐⭐

Questions Details:

Consider:

val generator = PasswordGenerator()
generator.seed = "someString"
generator.hash = {s -> someHash(s)}
generator.hashRepititions = 1000

val password: Password = generator.generate()

How would you refactor this code using run extension function?

See πŸ‘‰ Answer

Q55: Explain the difference between lateinit and lazy in details ⭐⭐⭐⭐⭐

See πŸ‘‰ Answer

Q56: What's wrong with that code? ⭐⭐⭐⭐⭐

Questions Details:

Let's say I want to override the Int getter so that it returns 0 if the value negative for the data class. What's bad with that approach?

data class Test(private val _value: Int) {
  val value: Int
    get() = if (_value < 0) 0 else _value
}

See πŸ‘‰ Answer

Q57: What is SAM Conversion in Kotlin? ⭐⭐⭐⭐⭐

See πŸ‘‰ Answer

Q58: What is the difference between β€œ*” and β€œAny” in Kotlin generics? ⭐⭐⭐⭐⭐

See πŸ‘‰ Answer

Q59: Why do we use β€œcompanion object” as a kind of replacement for Java static fields in Kotlin? ⭐⭐⭐⭐⭐

See πŸ‘‰ Answer

Q60: Imagine you moving your code from Java to Kotlin. How would you rewrite this code in Kotlin? ⭐⭐⭐⭐⭐

Questions Details:

public class Foo {
    private static final Logger LOG = LoggerFactory.getLogger(Foo.class);
}

See πŸ‘‰ Answer

Q61: How Kotlin coroutines are better than RxKotlin/RxJava? ⭐⭐⭐⭐⭐

See πŸ‘‰ Answer

Q62: What is the difference between launch/join and async/await in Kotlin coroutines? ⭐⭐⭐⭐⭐

See πŸ‘‰ Answer

Q63: What is a motivation to make classes final by default in Kotlin? Do you agree with that decision? ⭐⭐⭐⭐⭐

See πŸ‘‰ Answer

Q64: How does the reified keyword in Kotlin work? ⭐⭐⭐⭐⭐

See πŸ‘‰ Answer

Q65: What is The Billion Dollar Mistake? ⭐⭐⭐⭐⭐

See πŸ‘‰ Answer

Q66: What is the difference between Java field and Kotlin property? ⭐⭐⭐⭐⭐

See πŸ‘‰ Answer

Q67: How to implement Builder pattern in Kotlin? ⭐⭐⭐⭐⭐

See πŸ‘‰ Answer

Q68: When to use and do not use an inline function in Kotlin? ⭐⭐⭐⭐⭐

See πŸ‘‰ Answer

Releases

No releases published

Packages

No packages published