preloader
Kotlin Interview Questions

Top 50 Kotlin Interview Questions and Answers 2022 Preparation

author image

If you are looking for Kotlin Interview questions, then you are in right place. On this page, we have given mostly all the interview questions of Kotlin which are generally asked by the candidates in big MNCs interviews. Professionals and freshers can prepare from the given Kotlin Question and Answers and ace their interview round

About Kotlin: It is an open-source, statically typed, JVM-based programming language. It is used to make android applications, server-side applications, and others. We can say it is an updated version of Java and interoperable. We can use Kotlin and Java for a single project and it makes a good blend with Object-Oriented Programming (OOPs).

Kotlin Interview Questions

1. What is the working of Kotlin work on Android?

2. Why do we use Kotlin?

3. Differentiate between val and var?

4. Differentiate between the variable declaration with val and const?

5. How to make sure null safety in Kotlin?

6. Differentiate safe calls(?.) and null check(!!)?

7. Is Kotlin have a ternary operator just like in java?

8. Explain Elvis operator in Kotlin?

9. What is the Procedure to convert a Kotlin source file to a Java?

10. Tell the use of @JvmStatic, @JvmFiled, and @JvmOverloads in Kotlin?

11. Explain different data types in Kotlin?

12. Can we use primitive types in Kotlin like int, double, float?

13. Explain String Interpolation in Kotlin?

14. Explain destructuring in Kotlin?

15. At what time lateinit keyword in Kotlin is used?

16. How can I check if a lateinit variable has been initialized or not?

17. Differentiate between lateinit and lazy in Kotlin?

18. How == operator and === operator are different?

19. Describe forEach in Kotlin?

20. Explain data classes in Kotlin.

21. Tell the equivalent of Java static methods in Kotlin?

22. Differentiate between FlatMap and Map in Kotlin?

23. Differentiate between Array and List types in Kotlin?

24. Can we use the new keyword to instantiate a class object in Kotlin?

25. Describe visibility modifiers in Kotlin?

26. In kotlin, how to create a Singleton class?

27. Explain init blocks in Kotlin?

28. Describe types of constructors in Kotlin?

29. Is there any link between primary and secondary constructors?

30. Tell the default type of argument used in a constructor?

31. Explain Coroutines in Kotlin?

32. Describe the suspend function in Kotlin Coroutines?

33. Differentiate Launch and Async in Kotlin Coroutines?

34. What do you mean by function extension in Kotlin?

35. Name some features which are available in Kotlin but not in Java?

36. While working in Kotlin What to choose a switch or when?

37. Tell open keyword usage in Kotlin?

38. Explain lambdas expressions?

39. Describe Higher-Order functions in Kotlin?

40. Explain extension functions in Kotlin?

41. Explain infix function in Kotlin?

42. Explain the inline function in Kotlin?

43. Explain noinline in Kotlin?

44. Explain Reified types in Kotlin?

45. Explain operator overloading in Kotlin?

46. Explain the Ranges operator in Kotlin?

47. Explain pair and triple in Kotlin?

48. Describe labels in Kotlin?

49. Does Kotlin provide support for macros?

50. Explain the default behavior of Kotlin classes?


Learn More Interview Questions Here:


Kotlin Interview Questions and Answers

1. What is the working of Kotlin work on Android?

The Kotlin code is also accumulated into the Java bytecode and performed at runtime by the JVM (Java Virtual Machine). When Main.kt a kotlin file is compiled then it will ultimately turn into a class and then the bytecode is generated. The bytecode file name will be MainKt.class which will be executed by the JVM.

2. Why do we use Kotlin?

  • Kotlin is concise in nature
  • It is null-safe
  • It is interoperable

3. Differentiate between val and var?

If we want to state some mutable variable, then we use var. and for the immutable variable, we simply use val variables which can’t be changed once allocated.

4. Differentiate between the variable declaration with val and const?

Both the val and const variables are immutable in nature. But the difference is the value of the const variable should be known at compile-time whereas the val variable value can be allocated also at runtime.

5. How to make sure null safety in Kotlin?

It is one of the main advantages of using Kotlin is null safety. In Java, if you try to access a null variable then you will get a NullPointerException. So, the syntax code in Kotlin will generate a compile-time error:

var name: String = “MindOrks”

name = null //error

So, to allocate null values to a variable, you need to set the name variable as a nullable string, and then at the time of access, you need to use a safe call operator i.e. ?.

var name: String? = “MindOrks”

print(name?.length) // ok

name = null // ok

6. Differentiate safe calls(?.) and null check(!!)?

Safe call operator i.e. (?.) checks if the value of the variable whether it is null or not. If it is null then the null value is returned else it will bring back the desired value.

var name: String? = “MindOrks”

println(name?.length) // 8

name = null

println(name?.length) // null

If you use NullPointerException when the value is null, then we are able to use the null check or !! operator.

var name: String? = “MindOrks”

println(name?.length) // 8

name = null

println(name!!.length) // KotlinNullPointerException

7. Is Kotlin have a ternary operator just like in java?

No, Kotlin doesn’t have a ternary operator but to use the functionality you can use if-else or Elvis operator.

8. Explain Elvis operator in Kotlin?

To assign null values to a variable we use the null safety property. To know if a value is null value then we can use if-else or Elvis operator i.e. ?: For example:

var name:String? = “Mindorks”

val nameLength = name?.length ?: -1

println(nameLength)

The Elvis operator(?:) used in the above syntax returns the length of the name if the result is not null, if the value is null, then the value is displayed as -1.

9. What is the Procedure to convert a Kotlin source file to a Java?

  • Open your Kotlin project in the IntelliJ IDEA / Android Studio.
  • Then follow to Tools > Kotlin > Show Kotlin Bytecode options.
  • At last select Decompile button to get your Java code from the bytecode.

10. Tell the use of @JvmStatic, @JvmFiled, and @JvmOverloads in Kotlin?

@JvmStatic: This is used to tell that the method used in the compiler is a static method that can also be used as Java code.

@JvmField: It is used to access the fields of a Kotlin class from Java code without the use of any getters and setters.

@JvmOverloads: To use the default in Kotlin code from the Java code, we use this annotation.

11. Explain different data types in Kotlin?

Kotlin has different data types as objects. Some of the data types available in Kotlin are:

Integer Data Type -

| — | — | | Data Type | Space Required | | Byte | 8 bits | | Short | 16 bits | | Int | 32 bits | | Long | 64 bits |

Floating Point Data Type -

| — | — | | Data Type | Space Required | | Float | 32 bits | | Double | 64 bits |

Boolean Data Type -

Boolean data type represents an only a bit of information that is True or false. The Boolean type is the same as in Java.

| — | — | | Data Type | Space Required | | Boolean | 1 bit |

Character Data Type -

Small alphabets (a-z), capital alphabets (A-Z), numbers (0-9), and other special symbols come under character data type.

| — | — | | Data Type | Space Required | | Char | 8 bits |

String Data Type -

A string value is generally a sequence of characters that is kept in double quotations ("). The space requirement depends on the character’s numbers in the string.

Array Data Type -

It represents arrays. It has the get and set functions that, due to operator overloading conventions, can be used as ‘[]’ as well.

12. Can we use primitive types in Kotlin like int, double, float?

We are not able to use primitive types directly. We use these classes like Int, Double, etc. as an object wrapper for primitives. But the main compiled bytecode has these primitive types.

13. Explain String Interpolation in Kotlin?

If you do require the use of a variable or want to perform some operation inside a string then String Interpolation is required. The $ sign is used in some variable of the string or run some operation in between the {} sign.

var name = “MindOrks”

print(“Hello! I am learning from $name”)

14. Explain destructuring in Kotlin?

Destructuring is a method of extracting multiple values from stored data in (possibly nested) objects and Arrays. It is used for locations that receive data. Sometimes it is suitable to destructure an object into several variables, for example:

val (name, age) = developer

Now it can be named and aged independently like below:

println(name)

println(age)

15. At what time lateinit keyword in Kotlin is used?

lateinit is late initialization. Generally, the properties declaration of having a non-null type must be adjusted in the constructor. However, it is not fairly convenient. For example, if the properties are set through dependency injection, or in the setup method of a unit test. In this scenario, you are not able to supply a non-null initializer in the constructor, but still, you want to evade a null check. So, to handle this scenario, you can mark the property with the lateinit modifier.

16. How can I check if a lateinit variable has been initialized or not?

Before using the lateinit variable toy can check whether lateinit variable has been initialized or not by using a isInitialized method. The value comes true if the lateinit property is initialized, if not it will return false. For example: class Person { lateinit var name: String fun initializeName() { println(this::name.isInitialized) name = "MindOrks" // initializing name println(this::name.isInitialized) } } fun main(args: Array<String>) { Person().initializeName() }

17. Differentiate between lateinit and lazy in Kotlin?

lazy can be used as val properties, whereas lateinit is limited to var because as it cannot be compiled to a final field which results in no immutability is guaranteed. You need to use lateinit If you want your property to be initialized from outside.

18. How == operator and === operator are different?

The == operator is a way which compare the values stored in variables whereas the === operator checks the reference of the variables whether it is equal or not. But in primitive types, the === operator checks for the value and not the reference. //primitive example val int1 = 10 val int2 = 10 println(int1 == int2) // true println(int1 === int2) // true // wrapper example val num1 = Integer(10) val num2 = Integer(10) println(num1 == num2) // true println(num1 === num2) //false

19. Describe forEach in Kotlin?

If you want to use the functionality of a for-each loop as same as Java, then you require forEach function. Example:

var listOfMindOrks = listOf(“mindorks.com”, “blog.mindorks.com”, “afteracademy.com”)

listOfMindOrks.forEach {

Log.d(TAG,it)

}

20. Explain data classes in Kotlin.

The Data class contains data that provides typical functions. To set a data class, use the given syntax.

Syntax:

data class className ( list_of_parameters)

The following functions are compiled for the data classes:

  • equals(): - The function returns true if the given two content are identical. It operates the same as “==,” although Float and Double values work differently.
  • hashCode(): - It returns the object’s hashcode value.
  • copy(): This function duplicates the object, by modifying its few characteristics while leaving the rest as it is.
  • toString(): - It returns a string that has all of the data class’s parameters.

Follow Simple Steps to apply in these MNC’s:

21. Tell the equivalent of Java static methods in Kotlin?

To achieve the functionality which is the same as Java static methods in Kotlin, you can use:

  • companion object
  • package-level function
  • object

22. Differentiate between FlatMap and Map in Kotlin?

FlatMap helps in combining all the items of lists into one list, whereas Map can transform a list based on certain conditions.

23. Differentiate between Array and List types in Kotlin?

If you have a list of data of a fixed size, then Array can be used. But if the size of the list is different and varying in nature, then you need to use a mutable list.

24. Can we use the new keyword to instantiate a class object in Kotlin?

To represent a class object, simply we use the given syntax and cannot use the new keyword to instantiate a class object.

var varName = ClassName()

25. Describe visibility modifiers in Kotlin?

A visibility modifier is also called an access specifier or access modifier is a concept that describes the scope of something in a programming language. There are four visibility modifiers in Kotlin:

  • private: visible to a particular class or file containing the declaration.
  • protected: visible only to that particular class or file or subclass where it is declared.
  • internal: visible everywhere in that specific module.
  • public: visible to everyone.

26. In kotlin, how to create a Singleton class?

A singleton class is a class where only one instance of the class can be made and only be used where one instance of the class is required like in logging, database connections, etc. To generate a Singleton class use the object keyword as given in the syntax.

object AnySingletonClassName

27. Explain init blocks in Kotlin?

They are initializer blocks that perform just after the primary constructor. Class files can have one or more than one init blocks that will perform in series. If you execute some operation in the primary constructor then you need to use the init block as without using it you cannot perform it in kotlin.

28. Describe types of constructors in Kotlin?

Primary constructor: They are defined in the class header and you cannot perform some operation in it, unlike Java’s constructor.

Secondary constructor: the constructor keyword is used to declare them inside the class body. You need to call the primary constructor from the secondary constructor. Also, the class property cannot be declared inside the secondary constructor.

Yes, for using a secondary constructor, you do require to call the primary constructor explicitly.

30. Tell the default type of argument used in a constructor?

Val is the default type of argument of a constructor, but as per the requirement, you can change it to var explicitly.

31. Explain Coroutines in Kotlin?

A framework that manages concurrency with more efficient performance and simple way. It is a lightweight thread that is given on top of the actual threading framework to get the maximum output by using the cooperative nature of functions.

32. Describe the suspend function in Kotlin Coroutines?

This function is the building block whose functionality can be started, paused, and resume. To use this function, we use the suspend keyword in our normal function.

33. Differentiate Launch and Async in Kotlin Coroutines?

The main difference is that the launch{} will not return and the async{} returns with an instance of Deferred, which has an await() function that comes back with the result of the coroutine as same as we have future.get() I java to the get the result.

In other words:

  • launch: fire and forget
  • async: perform and comes back with a result

34. What do you mean by function extension in Kotlin?

In Kotlin, we easily add or remove method functionality using function extensions without inheriting or changing them. Extensions are solved statically. It is a function that is invoked with a dot operation than changing the existing class. We'll see how the function extension is implemented: // KOTLIN class Sample { var str : String = "null" fun printStr() { print(str) } } fun main(args: Array<String>) { var a = Sample() a.str = "Interview" var b = Sample() b.str = "Bit" var c = Sample() c.str = a.add(b) c.printStr() } // function extension fun Sample.add(a : Sample):String{ var temp = Sample() temp.str = this.str + " " +a.str return temp.str } Output:- Interview Bit

35. Name some features which are available in Kotlin but not in Java?

  • Null Safety
  • Operator Overloading
  • Coroutines
  • Range expressions
  • Smart casts
  • Companion Objects

36. While working in Kotlin What to choose a switch or when?

To handle many if-else conditions, we use switch-case statements. But Kotlin has a more sufficient option that is in Kotlin when can be used at a place of the switch as:

  • expression
  • arbitrary condition expression
  • without argument
  • with two or more choices

For example:

when(number) {

1 -> println(“One”)

2, 3 -> println(“Two or Three”)

4 -> println(“Four”)

else -> println(“Number is not between 1 and 4”)

}

37. Tell open keyword usage in Kotlin?

By default functionality, the classes, and functions are final in Kotlin. So, you can’t alter the class or take over the functions. If you want to do so, you do require an open keyword before the class and function.

38. Explain lambdas expressions?

Lambdas expressions are unidentified functions that can be treated as values like we can use the lambdas expressions as arguments towards a function to return them, or any other thing. For example:

val add : (Int, Int) -> Int = { a, b -> a + b }

val result = add(9, 10)

39. Describe Higher-Order functions in Kotlin?

It is a function that takes functions as parameters or bring back a function. For example, Functions as parameters. fun passMeFunction(abc: () -> Unit) { // I can take function // do something here // execute the function abc() } Function can bring back another function. fun add(a: Int, b: Int): Int { return a + b } And, we have a function returnMeAddFunction which takes zero parameters and returns a function of the type ((Int, Int) -> Int). fun returnMeAddFunction(): ((Int, Int) -> Int) { // can do something and return function as well // returning function return ::add } And to call the above function, we can do: val add = returnMeAddFunction() val result = add(2, 2)

40. Explain extension functions in Kotlin?

It is like an extensive property attached to any class in Kotlin. By using this function, you can add more functionalities to an existing class without inheriting it. For example:

fun View.show() {

this.visibility = View.VISIBLE

}

fun View.hide() {

this.visibility = View.GONE

}

and to use it we use, like,

toolbar.hide()

You may also prepare:

41. Explain infix function in Kotlin?

It calls a function without using any bracket or parenthesis. There is a specific infix keyword which is used for infix function. class Operations { var x = 10; infix fun minus(num: Int) { this.x = this.x - num } } fun main() { val opr = Operations() opr minus 8 print(opr.x) }

42. Explain the inline function in Kotlin?

Inline function commands compiler to add a complete body of the function wherever that function is used in the code. You need to add an inline keyword at the beginning of the function to use this function.

43. Explain noinline in Kotlin?

While using an inline function and you need to pass some lambda function and not all lambda functions as inline, then you can specifically tell the compiler which lambda to pass or which to keep through inline.

inline fun doSomethingElse(abc: () -> Unit, noinline xyz: () -> Unit) {

abc()

xyz()

}

44. Explain Reified types in Kotlin?

When you use the concept of Generics to pass some class as a parameter to some function for which you require to access the type of that class, then you do require the reified keyword in Kotlin. For example: inline fun <reified T> genericsExample(value: T) { println(value) println("Type of T: ${T::class.java}") } fun main() { genericsExample<String>("Learning Generics!") genericsExample<Int>(100) }

45. Explain operator overloading in Kotlin?

In Kotlin, we use the same operator to run various tasks which are called operator overloading. To do it, we need to tell a member function or an extension function with a proper name and operator keyword that comes before the function name it is because, when we use some operator then under the hood some function gets called. For eg., if you are writing num1+num2, then it changed to num1.plus(num2). For example: fun main() { val bluePen = Pen(inkColor = "Blue") bluePen.showInkColor() val blackPen = Pen(inkColor = "Black") blackPen.showInkColor() val blueBlackPen = bluePen + blackPen blueBlackPen.showInkColor() } operator fun Pen.plus(otherPen: Pen):Pen{ val ink = "$inkColor, ${otherPen.inkColor}" return Pen(inkColor = ink) } data class Pen(val inkColor:String){ fun showInkColor(){ println(inkColor)} }

46. Explain the Ranges operator in Kotlin?

Ranges operators keep iterating in a specific range. Its operator form is (..) For Example:

1. for (i in 1..15)

2. print(i)

The above example will give the result to print from 1 to 15.

47. Explain pair and triple in Kotlin?

As their name says, Pair and Triples return 2 and 3 values respectively from a function and the values which are returned can be of the same or different data types.

val pair = Pair(“My Age: “, 25)

print(pair.first + pair.second)

48. Describe labels in Kotlin?

Any expression in Kotlin is called a label. For example, if we are using a for-loop in Kotlin code then we can say a for-loop expression as a label and provide a label name for the for-loop.

A label can be created by using an identifier (@) sign. For example, name@, loop@, xyz@, etc. for example

loop@ for (i in 1..10) {

// some code goes here

}

The name of the above for-loop is a loop.

49. Does Kotlin provide support for macros?

No. Kotlin doesn’t provide support for macros as the developers of Kotlin have difficulty including them in the programming language.

50. Explain the default behavior of Kotlin classes?

In Kotlin all the classes are set as final by default, as Kotlin permits multiple inheritances for classes, and an open class is quite more costly than a final class.

Want to prepare for these languages:

If you are well-prepared with these questions then you can ace the round of Kotlin Interview Questions and answers. So prepare well and for any query, you can directly comment to us and we will surely resolve it as soon as possible.

Recent Articles