Giter VIP home page Giter VIP logo

kotlin-interview-questions's Introduction

๐Ÿ–ฒ Top 68 Kotlin interview questions (answered) for mobile app developers

Kotlin is a cross-platform, statically typed, general-purpose programming language with type inference. Kotlin is designed to interoperate fully with Java, and the JVM version of Kotlin's standard library depends on the Java Class Library, but type inference allows its syntax to be more concise. Kotlin mainly targets the JVM, but also compiles to JavaScript for frontend web applications using React or native code (via LLVM), e.g. for native iOS apps sharing business logic with Android apps. 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 2021.



You can also find all 68 answers here ๐Ÿ‘‰๐Ÿผ https://devinterview.io/dev/kotlin-interview-questions


๐Ÿ”น 1. 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ย  ย 


๐Ÿ”น 2. How to initialize an array in Kotlin with values?

Answer:

Problem

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?

val numbers: IntArray = intArrayOf(10, 20, 30, 40, 50)
Source:ย stackoverflow.comย  ย 


๐Ÿ”น 3. What is the idiomatic way to remove duplicate strings from array?

Answer:

Problem

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

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ย  ย 


๐Ÿ”น 4. 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ย  ย 


๐Ÿ”น 5. 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ย  ย 


๐Ÿ”น 6. 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ย  ย 


๐Ÿ”น 7. 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)

  2. 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ย  ย 


๐Ÿ”น 8. 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ย  ย 


๐Ÿ”น 9. 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ย  ย 


๐Ÿ”น 10. What is the difference between suspending vs. blocking?

Answer:

  • A blocking call to a function means that a call to any other function, from the same thread, will halt the parentโ€™s execution. Following up, this means that if you make a blocking call on the main threadโ€™s execution, you effectively freeze the UI. Until that blocking calls finishes, the user will see a static screen, which is not a good thing.

  • Suspending doesnโ€™t necessarily block your parent functionโ€™s execution. If you call a suspending function in some thread, you can easily push that function to a different thread. In case it is a heavy operation, it wonโ€™t block the main thread. If the suspending function has to suspend, it will simply pause its execution. This way you free up its thread for other work. Once itโ€™s done suspending, it will get the next free thread from the pool, to finish its work.

Source:ย www.raywenderlich.comย  ย 


๐Ÿ”น 11. val mutableList vs var immutableList. When to use which in Kotlin?

Answer:

Mutable and immutable list increase the design clarity of the model.
This is to force developer to think and clarify the purpose of collection.

  1. If the collection will change as part of design, use mutable collection
  2. If model is meant only for viewing, use immutable list

Purpose of val and var is different from immutable and mutable list.
val and var keyword talk about the how a value/reference of a variable should be treated.

  • var - value/reference assigned to a variable can be changed at any point of time.
  • val - value/reference can be assigned only once to a variable and can't be changed later point in the execution.

There are several reasons why immutable objects are often preferable:

  • They encourage functional programming, where state is not mutated, but passed on to the next function which creates a new state based on it. This is very well visible in the Kotlin collection methods such as map, filter, reduce, etc.
  • A program without side effects is often easier to understand and debug (you can be sure that the value of an object will always be the one at its definition).
  • In multithreaded programs, immutable resources cannot cause race conditions, as no write access is involved.

You have also some disadvantages:

  • Copying entire collections just to add/remove a single element is computationally expensive.
  • In some cases, immutability can make the code more complex, when you tediously need to change single fields. In Kotlin, data classes come with a built-in copy() method where you can copy an instance, while providing new values for only some of the fields.
Source:ย stackoverflow.comย  ย 


๐Ÿ”น 12. What is Lateinit in Kotlin and when would you use it?

Answer:

lateinit means late initialization. If you do not want to initialize a variable in the constructor instead you want to initialize it later on and if you can guarantee the initialization before using it, then declare that variable with lateinit keyword. It will not allocate memory until initialized. You cannot use lateinit for primitive type properties like Int, Long etc.

lateinit var test: String

fun doSomething() { test = "Some value" println("Length of string is "+test.length) test = "change value" }

There are a handful of use cases where this is extremely helpful, for example:

  • Android: variables that get initialized in lifecycle methods;
  • Using Dagger for DI: injected class variables are initialized outside and independently from the constructor;
  • Setup for unit tests: test environment variables are initialized in a @Before - annotated method;
  • Spring Boot annotations (eg. @Autowired).
Source:ย medium.comย  ย 


๐Ÿ”น 13. How are extensions resolved in Kotlin and what doest it mean?

Answer:

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

The extension functions dispatched statically. That means the extension function which will be called is determined by the type of the expression on which the function is invoked, not by the type of the result of evaluating that expression at runtime. In short, they are not virtual by receiver type.

Consider:

open class BaseClass

class DerivedClass : BaseClass()

fun BaseClass.someMethod(){ print("BaseClass.someMethod") }

fun DerivedClass.someMethod(){ print("DerivedClass.someMethod") }

fun printMessage(base : BaseClass){ base.someMethod() }

printMessage(DerivedClass())

This will print

BaseClass.someMethod

because the extension function being called depends only on the declared type of the parameter base in printMessage method, which is the BaseClass class. This is different from runtime polymorphism as here it is resolved statically but not at the runtime.

Source:ย medium.comย  ย 


๐Ÿ”น 14. May you briefly compare Kotlin vs Java?

Answer:

Java vs KotlinJavaKotlin
Null SafeIn Java, NullPointerExceptions causes huge frustration for developers. It allows users to assign null to any variables but while accessing an object reference having null value raises a null pointer exception which user needs to handle.In Kotlin, By default, all types of variables are non-null able (i.e. we canโ€™t assign null values to any type of variables/objects). If we try to assign or return null values, Kotlin code will fail during compile-time. If we really want a variable to have a null value, we can declare as follows: value num: Int? = null
Extension FunctionsIn Java, If we want to extend the functionality of existing class we need to create a new class and inherit the parent class. So Extension functions are not available in JavaKotlin provides developers the ability to extend an existing class with new functionality. We can create extend functions by prefixing the name of a class to name of the new function.
Coroutinesย SupportIn Java, whenever if we initiate a long-running network I/0 or CPU Intensive operations, the corresponding thread will be blocked. As Android is a single-threaded by default. Java provides the ability to create multiple threads in the background and run but managing them is a complex task.In Kotlin, We can create multiple threads to run these long-running intensive operations but we have coroutines support, which will suspend execution at a certain point without blocking threads while executing long-running intensive operations.
No checked exceptionsIn Java, We have checked exceptions support which makes developers declare and catch the exception which ultimately leads to robust code with good error handling.In Kotlin, we donโ€™t have checked exceptions. So developers donโ€™t need to declare or catch the exceptions, which have advantages and disadvantages.
Data classesIn Java, suppose we need to have a class which needs to hold data but nothing else. For this we need to define constructors, variables to store data, getter and setter methods, hashcode(), toString(), and equals() functionsIn Kotlin, If we need to have classes which need to hold data we can declare a class with keyword โ€œdataโ€ in the class definition then the compiler will take care of all of this work such as creating constructors, getter, setter methods for different fields.
Smart castsIn Java, We need to check the type of variables and cast according to our operation.In Kotlin, smart casts will handle these casting checks with keyword โ€œis-checksโ€ which will check for immutable values and performs implicit casting.
Type inferenceIn Java, we need to specify a type of each variable explicitly while declaring.In Kotlin, we donโ€™t need to specify the type of each variable explicitly based on assignment it will handle. If we want to specify explicitly we can do.
Functional ProgrammingJava doesnโ€™t have functional programming support till Java 8 but while developing Android applications it supports the only subset of Java 8 features.Kotlin is a mix of procedural and functional programming language which consists of many useful methods such as lambda, operator overloading, higher-order functions, and lazy evaluation, etc.
Source:ย www.educba.comย  ย 


๐Ÿ”น 15. What is the difference between const and val?

Answer:

consts are compile time constants. Meaning that their value has to be assigned during compile time, unlike vals, where it can be done at runtime.

This means, that consts can never be assigned to a function or any class constructor, but only to a String or primitive.

For example:

const val foo = complexFunctionCall()   //Not okay
val fooVal = complexFunctionCall()      //Okay

const val bar = "Hello world" //Also okay

Source:ย stackoverflow.comย  ย 


๐Ÿ”น 16. What are some disadvantages of Kotlin?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 17. Why would you use apply in Kotlin?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 18. Explain the Null safety in Kotlin

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 19. What is the idiomatic way to deal with nullable values, referencing or converting them?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 20. What is the equivalent of Java static methods in Kotlin?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 21. Explain advantages of when vs switch in Kotlin

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 22. May you use IntArray and an Array<Int> is in Kotlin interchangeably?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 23. What is suspending function in Kotlin?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 24. How would you create a singleton with parameter in Kotlin?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 25. When would you use Elvis operator in Kotlin?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 26. What is the Kotlin double-bang (!!) operator?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 27. What are scope functions in Kotlin?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 28. What are coroutines in Kotlin?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 29. What are the advantages of Kotlin over Java?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 30. What is a difference between a class and object in Kotlin?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 31. What is the purpose of Unit-returning in functions? Why is VALUE there? What is this VALUE?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 32. When to use lateinit over lazy initialization in Kotlin?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 33. Explain lazy initialization in Kotlin

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 34. What is the difference between List and Array types?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 35. What is a purpose of Companion Objects in Kotlin?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 36. How is it recommended to create constants in Kotlin?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 37. What is the difference between open and public in Kotlin?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 38. Explain what is wrong with that code?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 39. How would you refactor this code using apply?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 40. How to convert List to Map in Kotlin?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 41. What will be result of the following code execution?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 42. Rewrite this code in Kotlin

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 43. How can I create static method for enum in Kotiln?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 44. What is Kotlin backing field is used for?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 45. Explain the difference between Inline classes vs type aliases

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 46. Why is there no static keyword in Kotlin?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 47. What are Object expressions in Kotlin and when to use them?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 48. What is Coroutine Scope and how is that different from Coroutine Context?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 49. Provide a real use case when inline classes may be useful

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 50. What is the difference between launch/join and async/await in Kotlin coroutines?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 51. What is The Billion Dollar Mistake?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 52. How does the reified keyword in Kotlin work?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 53. How Kotlin coroutines are better than RxKotlin/RxJava?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 54. What is the difference between Java field and Kotlin property?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 55. When to use and do not use an inline function in Kotlin?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 56. What is a motivation to make classes final by default in Kotlin? Do you agree with that decision?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 57. Why do we use โ€œcompanion objectโ€ as a kind of replacement for Java static fields in Kotlin?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 58. What is SAM Conversion in Kotlin?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 59. What is the difference between * and Any in Kotlin generics?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 60. Explain the difference between lateinit and lazy in details

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 61. What is inline class in Kotlin and when do we need one? Provide an example.

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 62. How to create an instance of anonymous class of abstract class in Kotlin?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 63. How to create empty constructor for data class in Kotlin?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 64. Rewrite this code using run extension function

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 65. How would you override default getter for Kotlin data class?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 66. What's wrong with that code?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 67. How to implement Builder pattern in Kotlin?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


๐Ÿ”น 68. Imagine you moving your code from Java to Kotlin. How would you rewrite this code in Kotlin?

๐Ÿ‘‰๐Ÿผ Check all 68 answers


kotlin-interview-questions's People

Contributors

devinterview-io avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.