25+ [ MOST-POPULAR ] Kotlin Interview Questions & Answers | ACTE
Kotlin Interview Questions and Answers

25+ [ MOST-POPULAR ] Kotlin Interview Questions & Answers

Last updated on 04th Jul 2020, Blog, Interview Questions

About author

Amarnath (Sr Project Manager )

He is a Proficient Technical Expert for Respective Industry Domain & Serving 8+ Years. Also, Dedicated to Imparts the Informative Knowledge's to Freshers. He Share's this Blogs for us.

(5.0) | 16547 Ratings 2086

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.

1) What’s the Target Platform of Kotlin? How is Kotlin-Java interoperability possible?

Ans:

Java Virtual Machine(JVM) is the Target Platform of Kotlin. Kotlin is 100% interoperable with Java since both, on compilation produce bytecode. Hence Kotlin code can be called from Java and vice-versa.

2) How do you declare variables in Kotlin? How does the declaration differ from the Java counterpart?

Ans:

There are two major differences between Java and Kotlin variable declaration:

The type of declaration

In Java the declaration look like this:

  • String s = “Java String”;
  • int x = 10

In Kotlin the declaration looks like:

  • val s: String = “Hi”
  • var x = 5

In Kotlin, the declaration begins with a val and a var followed by the optional type. Kotlin can automatically detect the type using type inference.

Default value

The following is possible in Java:

  • String s;

The following variable declaration in Kotlin is not valid.

  • val s: String

3) What’s the difference between val and var declaration? How to convert a String to an Int?

Ans:

val variables cannot be changed. They’re like final modifiers in Java. A var can be reassigned. The reassigned value must be of the same data type.

  • fun main(args: Array<String>) {
  • val s: String = “Hi”
  • var x = 5
  • x = “6”.toInt()
  • }

We use the toInt() method to convert the String to an Int.

4) What’s Null Safety and Nullable Types in Kotlin? What is the Elvis Operator?

Ans:

Kotlin puts a lot of weight behind null safety which is an approach to prevent the dreaded Null Pointer Exceptions by using nullable types which are like String?, Int?, Float? etc. These act as a wrapper type and can hold null values. A nullable value cannot be added to another nullable or basic type of value.

To retrieve the basic types we need to use safe calls that unwrap the Nullable Types. If on unwrapping, the value is null we can choose to ignore or use a default value instead. The Elvis Operator is used to safely unwrap the value from the Nullable.

It’s represented as ?: over the nullable type. The value on the right hand side would be used if the nullable type holds a null.

  • var str: String? = “JournalDev.com”
  • var newStr = str?: “Default Value”
  • str = null
  • newStr = str?: “Default Value”

5) What’s a const? How does it differ from a val?

Ans:

By default val properties are set at runtime. Adding a const modifier on a val would make a compile-time constant.

A const cannot be used with a var or on its own.

A const is not applicable on a local variable.

6) Does Kotlin allow us to use primitive types such as int, float, double?

Ans:

No kotlin does not support primitive datatypes as like in java. At the language level, we cannot use the above-mentioned types. But the JVM bytecode that’s compiled does certainly have them.

7) What’s the entry point of every Kotlin Program?

Ans:

The main function is the entry point of every Kotlin program. In Kotlin we can choose not to write the main function inside the class. On compiling the JVM implicitly encapsulates it in a class.

The strings passed in the form of Array<String> are used to retrieve the command line arguments.

8) How is !! different from ?. in unwrapping the nullable values? Is there any other way to unwrap nullable values safely?

Ans:

!! is used to force unwrap the nullable type to get the value. If the value returned is a null, it would lead to a runtime crash. Hence a !! operator should be only used when you’re absolutely sure that the value won’t be null at all. Otherwise, you’ll get the dreaded null pointer exception. On the other hand, a ?. is an Elvis Operator that does a safe call.

We can use the lambda expression let on the nullable value to unwrap safely as shown below.

9) How is a function declared? Why are Kotlin functions known as top-level functions?

Ans:

fun sumOf(a: Int, b: Int): Int { return a + b }

10) What’s the difference between == and === operators in Kotlin?

Ans:

== is used to compare the values are equal or not. === is used to check if the references are equal or not.

11) List down the visibility modifiers available in Kotlin. What’s the default visibility modifier?

Ans:

  • public
  • internal
  • protected
  • private

public is the default visibility modifier.

12) Does the following inheritance structure compile?

Ans:

By default classes are final in Kotlin. To make them non-final, you need to add the open modifier.

  • open class A { }
  • class B : A() { }

13) What are the types of constructors in Kotlin? How are they different? How do you define them in your class?

Ans:

Constructors in Kotlin are of two types:

  • Primary — These are defined in the class headers. They cannot hold any logic. There’s only one primary constructor per class.
  • Secondary — They’re defined in the class body. They must delegate to the primary constructor if it exists. They can hold logic. There can be more than one secondary constructors.

14) What’s init block in Kotlin:

Ans:

init is the initializer block in Kotlin. It’s executed once the primary constructor is instantiated. If you invoke a secondary constructor, then it works after the primary one as it is composed in the chain.

15) How does string interpolation work in Kotlin? Explain with a code snippet?

Ans:

String interpolation is used to evaluate string templates.

We use the symbol $ to add variables inside a string.

  • val name = “Journaldev.com”

val desc = “$name now has Kotlin Interview Questions too. ${name.length}”

Using {} we can compute an expression too.

16) What’s the type of arguments inside a constructor?

Ans:

By default, the constructor arguments are val unless explicitly set to var.

17) Is new a keyword in Kotlin? How would you instantiate a class object in Kotlin?

Ans:

NO. Unlike Java, in Kotlin, new isn’t a keyword.

We can instantiate a class in the following way:

18) What is the equivalent of switch expression in Kotlin? How does it differ from switch?

Ans:

when is the equivalent of switch in Kotlin.

The default statement in a when is represented using the else statement.

Image for post

19) What are data classes in Kotlin? What makes them so useful? How are they defined?

Ans:

In Java, to create a class that stores data, you need to set the variables, the getters and the setters, override the toString(), hash() and copy() functions.

In Kotlin you just need to add the data keyword on the class and all of the above would automatically be created under the hood.

20) What are destructuring declarations in Kotlin? Explain it with an example.

Ans:

Destructuring Declarations is a smart way to assign multiple values to variables from data stored in objects/arrays.

Within paratheses, we’ve set the variable declarations. Under the hood, destructuring declarations create component functions for each of the class variables.

    Subscribe For Free Demo

    21) What’s the difference between inline and infix functions? Give an example of each.

    Ans:

    Inline functions are used to save us memory overhead by preventing object allocations for the anonymous functions/lambda expressions called. Instead, it provides that functions body to the function that calls it at runtime. This increases the bytecode size slightly but saves us a lot of memory.

    Image for post

    infix functions on the other are used to call functions without parentheses or brackets. Doing so, the code looks much more like a natural language.

    Image for post

    22) What’s the difference between lazy and lateinit?

    Ans:

    Both are used to delay the property initializations in Kotlin

    lateinit is a modifier used with var and is used to set the value to the var at a later point.

    lazy is a method or rather say lambda expression. It’s set on a val only. The val would be created at runtime when it’s required.

    • val x: Int by lazy { 10 }
    • lateinit var y: String

    23) How to create Singleton classes?

    Ans:

    To use the singleton pattern for our class we must use the keyword object

    An object cannot have a constructor set. We can use the init block inside it though.

    object MySingletonClass

    24) Does Kotlin have the static keyword? How to create static methods in Kotlin?

    Ans:

    NO. Kotlin doesn’t have the static keyword.

    To create static method in our class we use the companion object.

    Following is the kotlin code:

    • class A { companion object { fun a() : Int = 5 } }

    25) What’s the type of the following Array?

    Ans:

    • val arr = arrayOf(1, 2, 3);

    The type is Array<Int>. That’s all for Kotlin interview questions and answers.

    26) Explain Higher-Order Functions?

    Ans:

    Higher-Order Functions: A higher-order function is a function that takes functions as parameters, or returns a function.

    27) Can you execute Kotlin code without JVM?

    Ans:

    JVM, which stands for Java Virtual Machine is a feature of Kotlin. This feature compiles a Kotlin code into a native code, which can be done without JVM too.

    28) Mention the structural expressions in Kotlin?

    Ans:

    There are three Structural expressions in Kotlin.They are:

    • Return: It returns from the nearest enclosing function or anonymous function by default.
    • Break: This expression terminates the closest enclosing loop.
    • Continue: This expression proceeds you to the next closest enclosing loop.

    29) What are the types of strings available in Kotlin? And, what do you mean by Kotlin String Interpolation?

    Ans:

    Strings are a collection of characters together.Kotlin features two types of strings, and they are:

    • Raw string
    • Escaped string

    In Kotlin String, templates can be evaluated. This evaluation of string templates is called as the string template interpolation.

    30) State the advantages and disadvantages of Kotlin?

    Ans:

    Advantages:

    Kotlin is simple and easy to learn as its syntax is similar to that of Java.

    It is the functional language that is based on JVM (Java Virtual Machine), which removes the boilerplate codes. Upon all this, Kotlin is considered as an expressive language that is easily readable and understandable and the performance is substantially good.

    It can be used by any desktop, web server or mobile-based applications.

    Disadvantages:

    Kotlin does not provide the static modifier, which causes problems for conventional java developer.

    In Kotlin, the function declaration can be done in many places in the application, which creates trouble for the developer to understand which function is being called.

    Course Curriculum

    Get Experts Curated Kotlin Training with Industry Trends Concepts

    • Instructor-led Sessions
    • Real-life Case Studies
    • Assignments
    Explore Curriculum

    31) Which type of Programming does Kotlin support?

    Ans:

    Kotlin supports only two types of programming, and they are:

    • Procedural programming
    • Object-oriented programming

    32) What are Coroutines?

    Ans:

    A coroutine is a light-weight thread that doesn’t require any context switching on the processor and will not map on native threads. This is the reason why they are fast in processing the requests.

    33) Describe For Loops in Kotlin

    Ans:

    Loops are a crucial programming construct that allows us to iterate over things as our program requires. Kotlin features all the commonly used loops such as for, while, and do-while. We’re describing the for loop in a nutshell in the following section.

    • val sports = listOf(“cricket”, “football”, “basketball”)
    • for (sport in sports) { // for loop
    • println(“Let’s play $sport!”)
    • }

    The above snippet illustrates the use of the for loop in Kotlin. It’s quite similar to Python and Ruby.

    34) Describe While and Do-While Loops

    Ans:

    The while and do-while loops work quite similar but have a specific distinction. The do-while loop executes at least once, even if the first conditional expression is returned as false. Contrary to this, while loops will stop execution if the loop isn’t true at a given time.

    • var i = 1
    • while (i < 5) { // while loop
    • println(i)
    • i++
    • }

    This code will print the numbers 1 to 4 and then terminate. Now, take a look at the below do-while snippet.

    • var i = 6
    • do{ // do-while
    • println(i)
    • i++
    • }while(i<5)

    Although the condition to while is false, it will print the number 6 as its output. This happens since the execution of the do block takes place without checking the condition first.

    35) How do String Interpolations Work in Kotlin?

    Ans:

    String interpolations work with multiple placeholders and first evaluate their value to display the final string output. This final output will contain the corresponding values of the placeholders. The below code snippet will illustrate a simple example of Kotlin string interpolation.

    • fun main(args: Array<String>) { // String Interpolation
    • print(“Please enter your name here:”)
    • val name:String? = readLine()
    • print(“Hello, $name!”)
    • }

    Here, the Kotlin compiler first receives the user input and interpolates this value in place of the placeholder $name. The last line of the snippet is translated by the compiler as shown below –

    new StringBuilder().append(“Hello, “).append(name).append(“!”).toString()

    36) How to Convert Strings to Integer?

    Ans:

    It’s common for app developers to convert string to int for various reasons. Kotlin allows you to go about this in multiple ways. Below we’re demonstrating a simple Kotlin program for this purpose.

    • fun main(args: Array<String>) {
    •     for (string in args) {
    •         try {
    •             val parsedValue = string.toInt()
    •             println(“The parsed integer value is $parsedInt”)
    •        } catch (nfe: NumberFormatException) {
    •             // not a valid int
    •        }
    •    }
    • }

    You can also do this without using explicit try-catch blocks. For this, you’ll need to utilize the toIntOrNull() method.

    37) What’s the Difference Between const and val?

    Ans:

    Earlier we illustrated how to create variables that only contain fixed data using the val keyword. However, Kotlin offers the const keyword for creating constants like the C programming language. The key difference between val and const is their execution phase. Kotlin sets the properties of val at runtime by default. On the other hand, const is set by the compiler during the program’s compiler time.

    • const val str = “Fixed string!” // global variable
    • fun main(args: Array<String>) {
    • const val x = 4
    • const val str = “New string..” // local variable
    • }

    Additionally, you can not use const inside the local scope, thus the above code block will fail to compile. This modifier is also not applicable on var.

    38) What’s the Entry Point for Kotlin Programs?

    Ans:

    Kotlin, like many popular programming languages, relies on a specific entry point. The main() function is this point, similar to other OOP languages such as C++ and Java. Developers can easily define the command-line arguments taken by Kotlin programs. For this, you’ll need to pass args: Array<String> to this main() function.

    It takes a somewhat different syntax than traditional Java programs. Below we’re illustrating the differences between the main() function in both Java and Kotlin. You can easily compare them for a better understanding.

    • public static void main(String[] args) // Entry to Java Programs
    • fun main(args: Array<String>) // Entry to Kotlin Programs

    39) Write a Kotlin Program to Display the Fibonacci Series

    Ans:

    Most Kotlin interview questions aim to find out the knowledge of the candidates for practical problems. The Fibonacci series is a common question faced by job seekers in many Kotlin interviews. It’s a mathematical sequence of numbers where each number is the sum of its previous two numbers.

    • fun main(args: Array<String>) {
    • val range = 10
    • var firstNumber = 0
    • var secondNumber = 1
    • print(“First $range numbers of Fibonacci series: “)
    • for (i in 1..range) {
    • print(“$firstNumber + “)
    • val sum = firstNumber + secondNumber
    • firstNumber = secondNumber
    • secondNumber = sum
    • }
    • }

    40) Why did you switch to Kotlin from Java ?

    Ans:

    Kotlin seems to be simpler and cleaner than Java. It removes a lot of redundancies in code from Java. Kotlin also adds some needed features that Java doesn’t yet support, and is making code more idiomatic. Also Kotlin has been added to Android Studio’s list of supported languages recently. So, there is much to expect from Kotlin in easing out the development efforts and good support in future.

    41) What are the features you think are there in Kotlin but not in Java ?

    Ans:

    Kotlin has quite a number of features that Java doesn’t. To name some of them, they are

    • Extension Functions
    • Null Safety
    • Smart casts
    • Range expressions
    • Operator Overloading
    • Data classes
    • Companion Objects
    • Coroutines
    • etc.

    42) What kinds of programming does Kotlin support ?

    Ans:

    Kotlin supports two types of programming. They are

    • Procedural Programming
    • Object Oriented Programming

    43) What is the entry point to a Kotlin program ? Provide an example.

    Ans:

    Like most of the other procedural languages, main() function is the entry point to a Kotlin program.

    An Example for main() function is :

    •  fun main(args: Array<String>) {   
    •  val user1 = User(name=”Yogi”, age=27)  
    •   printUser(user1)}fun printUser(user: User){  
    •   println(user)}
    • data class User(val name: String, val age: Int); 

    44) How do you think extension functions are useful ? 

    Ans:

    Extension functions helps to extend a class with new functionality without having to inherit from the class. Also you may use them like an inbuilt function for the class throughout the application.

    45) What are Data classes ? Aren’t they available in Java ? 

    Ans:

    Sometimes we use a class just to hold the data and nothing else. These classes are called Data classes. Of course these kind of classes could be built using Java, but with explicit implementation of getter and setter for each of the properties of class. Also you may need to implement functions like equals, toString and copy separately. What Kotlin does is implementing all these automatically along with special functions called component functions. How cool is that, removing the redundant code bloat.

    46) Does Kotlin provide any additional functionalities for standard Java packages or standard Java classes?

    Ans:

    Ofcourse, Yes. Kotlin uses the concept of extension functions, that we already talked about, to build some useful and more widely used functions among developers directly into the Kotlin library.

    47)  Where does this Kotlin run ? Does it have some kind of different runtime environment ?

    Ans:

    Once compiled, Kotlin programs can run on standard JVM like some other compiled Java code. This means that Kotlin Compiler compiles Kotlin programs to byte-code, which is understood by JVM. So, Kotlin is like a flavor of Java, that goes alongside Java. Interesting fact is that, Kotlin applications can be built with parts of Java code.

    48) So, how do you migrate the code from Java to Kotlin ?

    Ans:

    JetBrains IDEA provides inbuilt tools to convert Java code to Kotlin code. Then you may do the magic offered by Kotlin at some of the parts in code, to make it clean.

    49) Is there something called init block in Kotlin ?

    Ans:

    Yes.

    50) What does init block do and Where does it appear in a class ? 

    Ans:

    Instructions in the init block are executed right after Primary Constructor’s execution. init block goes in a class along with secondary constructors as a method.

    Course Curriculum

    Get Practical Oriented Kotlin Certification Course By Experts Trainers

    Weekday / Weekend BatchesSee Batch Details

    51) How many types of constructors are there ? What are they ?

    Ans:

    There are two types of constructors. They are Primary Constructors and Secondary Constructors.

    52) How are Primary Constructors different from Secondary Constructors ?

    Ans:

    Primary Constructors are declared intrinsically with class definition. Secondary Constructors are declared exclusively inside the class body.

    In the following example, in the first line, the constructor keyword along with the variables declared right after it is the Primary Constructor. Inside the class body, we have another constructor, and this is Secondary Constructor.

    Example of class with Primary and Secondary Constructors

    • class Person constructor(var name: String, var age: Int){   
    •  var profession: String = “Not Mentioned”        
    • constructor (name: String, age: Int, profession: String): this(name,age){      
    •   this.profession = profession   
    •  }} 

    53) Is there any dependency of Secondary Constructors on Primary Constructors ?

    Ans:

    Yes. Secondary Constructor has to make an exclusive call to Primary Constructor or other Secondary Constructor, which of course calls the Primary Constructor. Following is an example, and here the Secondary Constructor makes call to Primary Constructor using this(name, age).

    Example of class with Primary and Secondary Constructors

    • class Person constructor(var name: String, var age: Int){   
    •  var profession: String = “Not Mentioned”        
    • constructor (name: String, age: Int, profession: String): this(name,age){       
    •  this.profession = profession    }      
    •   fun printPersonDetails(){       
    •  println(“$name whose profession is $profession, is $age years old.”)  
    •   }} 

    54) What is the difference between val and var ?

    Ans:

    Val (Value) is like a constant. Once assigned a value, you cannot change it. On the other hand Var (Variable) is designed to be a storage location that can accept reassignment of values of same data type or what ever feasible by the data type casting.

    55) What is Kotlin’s Null Safety ? 

    Ans:

    Null Safety in Kotlin is to eliminate the risk of occurrence of NullPointerException in real time. Kotlin can differentiate between nullable references and non-nullable references. If a variable has to be allowed to store a null value, that has to be declared with a null (?) operator.

    56) If you have worked with files, name some of the extension methods Kotlin provides to java.io.File

    Ans:

    Kotlin provides very useful extension functions to java.io.File. Some of them are :

    • File.bufferedReader() : to read contents of a file into BufferedReader
    • File.forEachLine() : to read a file line by line in Kotlin
    • File.inputStream() : to read contents of file to InputStream
    • File.readBytes() : to read contents of file to ByteArray
    • File.readLines() : to read lines in file to List
    • File.readText() : to read contents of file to a single String

    57) Is there a Ternary Conditional Operator in Kotlin like in Java ?

    Ans:

    No.

    58) How do you realize Ternary Conditional Operator in Kotlin ?

    Ans:

    A simple if else should do the job.

    •  if (condition) a else b 

    59) How do you declare a variable as volatile in Kotlin ? 

    Ans:

    By providing volatile annotation before the declaration of variable.

    •  @Volatile var a: Long? = null 

    60) How do you check if two Strings are equal valued ? 

    Ans:

    Using == (double equal to) operator.

    61) How does Kotlin work on Android?

    Ans:

    Just like Java, the Kotlin code is also compiled into the Java bytecode and is executed at runtime by the Java Virtual Machine i.e. JVM. When a Kotlin file named Main.kt is compiled then it will eventually turn into a class and then the bytecode of the class will be generated. The name of the bytecode file will be MainKt.class and this file will be executed by the JVM.

    62) Why should we use Kotlin?

    Ans:

    • Kotlin is concise
    • Kotlin is null-safe
    • Kotlin is interoperable

    63) What is the difference between the variable declaration with var and val?

    Ans:

    If you want to declare some mutable(changeable) variable, then you can use var. For the immutable variable, use val i.e. val variables can’t be changed once assigned.

    64) What is the difference between the variable declaration with val and const?

    Ans:

    Both the variables that are declared with val and const are immutable in nature. But the value of the const variable must be known at the compile-time whereas the value of the val variable can be assigned at runtime also.

    65) How to ensure null safety in Kotlin?

    Ans:

    One of the major advantages of using Kotlin is null safety. In Java, if you access some null variable then you will get a NullPointerException. So, the following code in Kotlin will produce a compile-time error:

    • var name: String = “MindOrks”
    • name = null //error

    So, to assign null values to a variable, you need to declare the name variable as a nullable string and then during the access of this variable, you need to use a safe call operator i.e. ?.

    • var name: String? = “MindOrks”
    • print(name?.length) // ok
    • name = null // ok

    66) What is the difference between safe calls(?.) and null check(!!)?

    Ans:

    Safe call operator i.e. ?. is used to check if the value of the variable is null or not. If it is null then null will be returned otherwise it will return the desired value.

    • var name: String? = “MindOrks”
    • println(name?.length) // 8
    • name = null
    • println(name?.length) // null

    If you want to throw NullPointerException when the value of the variable is null, then you can use the null check or !! operator.

    • var name: String? = “MindOrks”
    • println(name?.length) // 8
    • name = null
    • println(name!!.length) // KotlinNullPointerException

    67) Do we have a ternary operator in Kotlin just like java?

    Ans:

    No, we don’t have a ternary operator in Kotlin but you can use the functionality of ternary operator by using if-else or Elvis operator.

    68) What is Elvis operator in Kotlin?

    Ans:

    In Kotlin, you can assign null values to a variable by using the null safety property. To check if a value is having null value then you can use if-else or can use the Elvis operator i.e. ?: For example:

    • var name:String? = “Mindorks”
    • val nameLength = name?.length ?: -1
    • println(nameLength)

    The Elvis operator(?:) used above will return the length of name if the value is not null otherwise if the value is null, then it will return -1.

    • fun main(args: Array<String>) {  
    •   val a: String = “kotlin is easy”    
    • val b: String = “kotlin is” + ” easy”    if(a==b){     
    •    println(” a and b are equal.”)    }
    • else {        println(” a and b are not equal.”) 
    •    }} 

    69) How to convert a Kotlin source file to a Java source file?

    Ans:

    Steps to convert your Kotlin source file to Java source file:

    • Open your Kotlin project in the IntelliJ IDEA / Android Studio.
    • Then navigate to Tools > Kotlin > Show Kotlin Bytecode.
    • Now click on the Decompile button to get your Java code from the bytecode.

    70) What is the use of @JvmStatic, @JvmOverloads, and @JvmFiled in Kotlin?

    Ans:

    • @JvmStatic: This annotation is used to tell the compiler that the method is a static method and can be used in Java code.
    • @JvmOverloads: To use the default values passed as an argument in Kotlin code from the Java code, we need to use the @JvmOverloads annotation.
    • @JvmField: To access the fields of a Kotlin class from Java code without using any getters and setters, we need to use the @JvmField in the Kotlin code.
    Kotlin Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

    71) What is a data class in Kotlin?

    Ans:

    Data classes are those classes which are made just to store some data. In Kotlin, it is marked as data. The following is an example of the same:

    • data class Developer(val name: String, val age: Int)

    When we mark a class as a data class, you don’t have to implement or create the following functions like we do in Java: hashCode(), equals(), toString(), copy(). The compiler automatically creates these internally, so it also leads to clean code. Although, there are few other requirements that data classes need to fulfill.

    72) Can we use primitive types such as int, double, float in Kotlin?

    Ans:

    In Kotlin, we can’t use primitive types directly. We can use classes like Int, Double, etc. as an object wrapper for primitives. But the compiled bytecode has these primitive types.

    73) What is String Interpolation in Kotlin?

    Ans:

    If you want to use some variable or perform some operation inside a string then String Interpolation can be used. You can use the $ sign to use some variable in the string or can perform some operation in between {} sign.

    • var name = “MindOrks”
    • print(“Hello! I am learning from $name”)

    74) What do you mean by destructuring in Kotlin?

    Ans:

    Destructuring is a convenient way of extracting multiple values from data stored in(possibly nested) objects and Arrays. It can be used in locations that receive data (such as the left-hand side of an assignment). Sometimes it is convenient to destructure an object into a number of variables, for example:

    • val (name, age) = developer

    Now, we can use name and age independently like below:

    • println(name)
    • println(age)

    75) When to use the lateinit keyword in Kotlin?

    Ans:

    lateinit is late initialization.

    Normally, properties declared as having a non-null type must be initialized in the constructor. However, fairly often this is not convenient.

    For example, properties can be initialized through dependency injection, or in the setup method of a unit test. In this case, you cannot supply a non-null initializer in the constructor, but you still want to avoid null checks when referencing the property inside the body of a class. To handle this case, you can mark the property with the lateinit modifier.

    76) How to check if a lateinit variable has been initialized or not?

    Ans:

    You can check if the lateinit variable has been initialized or not before using it with the help of isInitialized method. This method will return true if the lateinit property has been initialized otherwise 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()
    • }

    77) What is the difference between lateinit and lazy in Kotlin?

    Ans:

    • lazy can only be used for val properties, whereas lateinit can only be applied to var because it can’t be compiled to a final field, thus no immutability can be guaranteed.
    • If you want your property to be initialized from outside in a way probably unknown beforehand, use lateinit.

    78) Is there any difference between == operator and === operator?

    Ans:

    Yes. The == operator is used to compare the values stored in variables and the === operator is used to check if the reference of the variables are equal or not. But in the case of primitive types, the === operator also checks for the value and not 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

    79) What is the forEach in Kotlin?

    Ans:

    In Kotlin, to use the functionality of a for-each loop just like in Java, we use a forEach function. The following is an example of the same:

    • var listOfMindOrks = listOf(“mindorks.com”, “blog.mindorks.com”, “afteracademy.com”)
    • listOfMindOrks.forEach {
    •  Log.d(TAG,it)
    • }

    80) What are companion objects in Kotlin?

    Ans:

    In Kotlin, if you want to write a function or any member of the class that can be called without having the instance of the class then you can write the same as a member of a companion object inside the class.

    To create a companion object, you need to add the companion keyword in front of the object declaration.

    The following is an example of a companion object in Kotlin:

    • class ToBeCalled {
    •  companion object Test {
    •  fun callMe() = println(“You are calling me :)”)
    •  }
    • }
    • fun main(args: Array<String>) {
    •  ToBeCalled.callMe()
    • }

    81) What is the equivalent of Java static methods in Kotlin?

    Ans:

    To achieve the functionality similar to Java static methods in Kotlin, we can use:

    • companion object
    • package-level function
    • object

    82) What is the difference between FlatMap and Map in Kotlin?

    Ans:

    • FlatMap is used to combine all the items of lists into one list.
    • Map is used to transform a list based on certain conditions.

    83) What is the difference between List and Array types in Kotlin?

    Ans:

    If you have a list of data that is having a fixed size, then you can use an Array. But if the size of the list can vary, then we have to use a mutable list.

    84) Can we use the new keyword to instantiate a class object in Kotlin?

    Ans:

    No, in Kotlin we don’t have to use the new keyword to instantiate a class object. To instantiate a class object, simply we use:

    var varName = ClassName()

    85) What are visibility modifiers in Kotlin?

    Ans:

    A visibility modifier or access specifier or access modifier is a concept that is used to define the scope of something in a programming language. In Kotlin, we have four visibility modifiers:

    • private: visible inside that particular class or file containing the declaration.
    • protected: visible inside that particular class or file and also in the subclass of that particular class where it is declared.
    • internal: visible everywhere in that particular module.
    • public: visible to everyone.

    86) How to create a Singleton class in Kotlin?

    Ans:

    A singleton class is a class that is defined in such a way that only one instance of the class can be created and is used where we need only one instance of the class like in logging, database connections, etc.

    To create a Singleton class in Kotlin, you need to use the object keyword.

    object AnySingletonClassName

    87) What are init blocks in Kotlin?

    Ans:

    init blocks are initializer blocks that are executed just after the execution of the primary constructor. A class file can have one or more init blocks that will be executed in series. If you want to perform some operation in the primary constructor, then it is not possible in Kotlin, for that, you need to use the init block.

    88) Is there any relationship between primary and secondary constructors?

    Ans:

    Yes, when using a secondary constructor, you need to call the primary constructor explicitly.

    89) What is the default type of argument used in a constructor?

    Ans:

    By default, the type of arguments of a constructor in val. But you can change it to var explicitly.

    90) What are Coroutines in Kotlin?

    Ans:

    A framework to manage concurrency in a more performant and simple way with its lightweight thread which is written on top of the actual threading framework to get the most out of it by taking the advantage of cooperative nature of functions.

    91) What is suspend function in Kotlin Coroutines?

    Ans:

    Suspend function is the building block of the Coroutines in Kotlin. Suspend function is a function that could be started, paused, and resume. To use a suspend function, we need to use the suspend keyword in our normal function definition.

    92) What is the difference between Launch and Async in Kotlin Coroutines?

    Ans:

    The difference is that the launch{} does not return anything and the async{} returns an instance of Deferred<T>, which has an await() function that returns the result of the coroutine like we have future in Java in which we do future.get() to the get the result.

    In other words:

    • launch: fire and forget
    • async: perform a task and return a result

    93) How to choose between a switch and when in Kotlin?

    Ans:

    Whenever we want to handle many if-else conditions, then we generally use switch-case statements. But Kotlin provides a more concise option i.e. in Kotlin, we can use when in place of the switch. And, when can be used 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”)
    • }

    94) What is the open keyword in Kotlin used for?

    Ans:

    By default, the classes and functions are final in Kotlin. So, you can’t inherit the class or override the functions. To do so, you need to use the open keyword before the class and function. For example:

    95) What are lambdas expressions?

    Ans:

    Lambdas expressions are anonymous functions that can be treated as values i.e. we can pass the lambdas expressions as arguments to a function return them, or do any other thing we could do with a normal object. For example:

    • val add : (Int, Int) -> Int = { a, b -> a + b }
    • val result = add(9, 10)

    96) What are Higher-Order functions in Kotlin?

    Ans:

    A higher-order function is a function that takes functions as parameters or returns a function. For example, A function can take functions as parameters.

    • fun passMeFunction(abc: () -> Unit) {
    •  // I can take function
    •  // do something here
    •  // execute the function
    •  abc()
    • }
    >

    For example, A function can return 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)

    97) What are extension functions in Kotlin?

    Ans:

    Extension functions are like extensive properties attached to any class in Kotlin. By using extension functions, you can add some methods or functionalities to an existing class even without inheriting the class. For example: Let’s say, we have views where we need to play with the visibility of the views. So, we can create an extension function for views like,

    • fun View.show() {
    •  this.visibility = View.VISIBLE
    • }
    • fun View.hide() {
    •  this.visibility = View.GONE
    • }
    • and to use it we use, like,
    • toolbar.hide()

    98) What is an infix function in Kotlin?

    Ans:

    An infix function is used to call the function without using any bracket or parenthesis. You need to use the infix keyword to use the 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)
    • }

    99) What is an inline function in Kotlin?

    Ans:

    Inline function instruct compiler to insert complete body of the function wherever that function got used in the code. To use an Inline function, all you need to do is just add an inline keyword at the beginning of the function declaration.

    Are you looking training with Right Jobs?

    Contact Us
    Get Training Quote for Free