Kotlin Interview Questions

Kotlin Interview Questions | Freshers & Experienced

  • Om Prakash
  • 12th Apr, 2021
  • 449 Followers

Key Features of Kotlin

Below are few major features of Kotlin

Open source

Full Java Interoperability

Null Safety

Write less code

Clean and compact syntax

Immutability

Operator overloading

Cross Platform

Easy to Maintain

Q1. What is the difference between object { } block and companion object { } code block in Kotlin?

Q2. What is the lateinit modifier used for?

lateinit modifier in Kotlin is used to delay the initialization of a variable.

The requirement of using lateinit modifier

  • These variables must be declared using var keyword, val is not allowed.
  • Must be either a property inside the body of a class or a top-level property
  • Can only be of non-null type
  • Primitive types disallowed

Declaration Syntax

lateinit var myVar: MyObject

Q3. What is Elvis Expression in Kotlin?

The Elvis operator in Kotlin is an operator that receives two inputs and returns the first argument if it is non-null or the second one otherwise. It is fancily called the null-coalescing operator. It is a variant of the ternary operator but for null-safety checking.

Example

x ?: y // yields `x` if `x` is not null, `y` otherwise.

Q4. For what vararg keyword in Kotlin used for?

Vararg (variable number of arguments) is a parameter in Kotlin where we can pass 'n' number of arguments of a defined datatype or a generic datatype. To simply put, vararg allows a variable number of arguments to be passed to the function. This parameter is normally used as the last parameter of a function.

Q5. What are High Level Functions in Kotlin?

A higher order or high level function is a function that accepts or return another function.

Q6. What are Coroutines?

Coroutines are light weight thread in Kotlin that convert async callbacks for long-running tasks, such as database or network access, into sequential code.

Defining a simple Coroutine

coroutine {
    progress.visibility = View.VISIBLE
 
    val user = suspended { userService.doLogin(username, password) }
    val currentFriends = suspended { userService.requestCurrentFriends(user) }
 
    val finalUser = user.copy(friends = currentFriends)
    toast("User ${finalUser.name} has ${finalUser.friends.size} friends")
 
    progress.visibility = View.GONE
}

Above is comman structure for a coroutine that have have a coroutine builder, and a set of suspending functions that will suspend the execution of the coroutine until they have the result.

Q7. What is diffrence between Val and Var?

The major difference between var and val in Kotlin is:

A variable declared with var is a mutable variable that value can be changed any time whereas variable declared with val keyword are final their value that not be changed.

They are both used to declare a variable.

The variables declared as var can be assigned multiple times. It can be read and write. So, it is called a mutable variable.

var y: String = "my String" // y can be reassigned.

The variables declared as val is a constant one and cannot be changed or assigned multiple times. It is initialized only once and can be read-only. It is called an Immutable variable.

val y: Double = 21.5 // y is constant.

Q8. What are different types of constructors available in Kotlin?

Constructors are used to initializing the properties of a class. There are two types of Constructors available in Kotlin.

Primary constructor: It is declared at the class header level.

Example

 
class User(val name: String, var age: Int) {
    // class body
}

Secondary constructor: In Kotlin you can create one or more secondary constructors using the "constructor" keyword. Example

class UserProfile {
    constructor(data: String) {
        // some code
    }
    constructor(data: String, numberOfData: Int) {
        // some code
    }
}

Q9. Why is Kotlin preferred over Java?

KOTLIN IS PREFERRED OVER JAVA because it requires fewer lines of codes to solve the same problem in JAVA. It is safer as it prevents common programming errors by design which may lead to system failures or application crashes. It has better support for functional programming. Here the performance can be made better through inlining, which is not presently possible in JAVA. Kotlin has a variety of handy features that speeds up everyday development tasks that are not provided by JAVA. The compiler of Kotlin runs many checks to prevent runtime errors and thereby reducing the cost and effort of error fixes.

Q10. Explain Kotlin's Null safety?

KOTLIN NULL SAFETY is a feature of its compiler which by default doesn’t allow any types to have a null value at compile type. It is also referred to as The Billion Dollar Mistake, which is to be removed from the code. It is the most common drawback of many programming languages, including JAVA. The access member of a null reference that will result in a null reference exception. In Kotlin by default, variables are non-null references and therefore cannot be set to null. NPE or NULL POINTER EXCEPTION are used for security vulnerabilities, especially for security-related code or processes. It is defensive programming which helps to make sure that our application still functions under unexpected conditions

Q11. What it the main the difference between lazy and lateinit in Kotlin?

Difference between lazy and lateinit in Kotlin

LATEINIT in Property Initialization refers to the late initialization. In this type of property initialization property has not been null or primitive type and must be initialized in the constructor. Here the modifier can only be used on VAR properties declared inside the body of the class and only when it does not have a custom setter or getter. It can be initialized from anywhere the object is seen from. Example

public class Test {

  lateinit var mock: Mock

  @SetUp fun setup() {
     mock = Mock()
  }

  @Test fun test() {
     mock.do()
  }
}

Lazy is lazy initialization. The LAZY () function takes a lambda and returns an instance of lazy that serves as a delegate for implementing a lazy property. It can only be applied to VARS as it cannot be compiled to a final field, thereby no immutability can be guaranteed. They are required to be initialized once and shared by all and is set internally. Example

public class Example{
  val name: String by lazy { "Coursey" }
}

Q12. How to define Constant in Kotlin.

Val keyword is used to define a Constant in Kotlin.

Syntax for defining a Local Constant in Kotlin.

val firstName: String = "Chike"

Creating a public constant in Kotlin like Java public static final

companion object{

     const val MY_CONSTANT = "Constants"

}

Q13. What is difference between inline and infix functions in Kotlin?

Difference between inline and infix functions in Kotlin

INLINE FUNCTIONS are used when we want to reduce the memory overhead, but they usually increase the resulting bytecode. In Kotlin, inlining is done with the inline keyword, which affects both the functions and arguments that are lambdas. It is a default setting for the compiler. We have to use a non-inline keyword to make lambda arguments not inlined.

INFIX FUNCTIONS is a particular type of function which needs specific rules to satisfy. It can be invoked through infix notation. This function needs to be attached to a class, either because it is a member or an extension where the single parameter still applies.

Q14. What is suspend in Kotlin?

Suspend is a function in Kotlin Coroutines. A suspending function is simply a function that can be paused and resumed at a later time. They can execute a long-running operation and wait for it to complete without blocking.

Q15. How to create AsyncTask in Android with Kotlin ?

The AsyncTask is used to execute long operations in the background. It is created to be a helper class around Thread and Handler.

The three types used by the AsyncTask are Params, Progress, and Result.

Different methods that are executed with the AsyncTask are PreExecute, doInBackgroud, onProgressUpdate, onPostExecute. Developers need to extend the class to create the AsyncTask. That is, the AyncTask should be subclassed to be used by the developers.

//syntax for creating an AsyncTask
inner class SomeTask extends AsyncTask<Params,Progress,Result>

Q16. Explain Launch vs Async in Kotlin ?

Both Launch and async are coroutines in Kotlin.

Launch: It is used to fire and forget coroutine. It is like starting a new thread. If the code inside the launch terminates with an exception, then it is treated like an uncaught exception in a thread -- usually printed to stderr in backend JVM applications and crashes Android applications.

Async: It is used to start a coroutine that computes some results. The result is represented by an instance of Deferred and you must use await on it. An uncaught exception inside the async code is stored inside the resulting Deferred and is not delivered anywhere else, it will get silently dropped unless processed.

Q17. What is Kotlin?

Kotlin is a relatively new programming language developed by the team behind JetBrains as an alternative to Java. Mainly used in the development of Android applications, Kotlin is a statically typed, general-purpose programming language with type inference. More streamlined and easy to interpret than Java, Kotlin mainly targets the JVM but also compiles to JavaScript or native code. Officially supported by Google for Android development, Koltlin has its compiler as an alternative to the standard Java compiler in the Android studio.

Q18. Enlist major features of Kotlin?

Kotlin was developed to make it feature-rich in mind, so there are many features that make Kotlin a unique programming language.

Below are some major Features of Kotlin Programming Language:

  • Extension functions: In Kotlin, you can add some extra functionality to the existing component to make it much more versatile.
  • Higher-Order Function: You can pass a function as an argument to a method or return a function as a result of the method in Kotlin.
  • Smart Cast: Smart Cast checks for some type, and then it will allow performing all the operations allowed for that particular type.
  • Destruction Declaration: With this, it is possible to return more than one value from a function.
  • Default and Named arguments: You can assign a default value to the parameter whom you want to make optional, and while calling that method, there is no bound on giving values to the default parameters. You can easily change the sequence of the parameter at the time of calling with Named arguments. It is done by writing the name of the argument and then assigning the value to it.

Q19. Why Kotlin is preffered over Java?

The code written in Kotlin is much more concise than Java. That is, you can solve the same problem with fewer lines of code in Kotlin. By default, Kotlin has better support for functional programming than Java, and Kotlin eliminates a big drawback in Java, the null pointer exception. It is also easy to learn, less prone to errors, and fully interoperable with Java. It also removes tons of boilerplate code that comes with Java and saves space and typing effort. For these reasons, Kotlin is preferred over Java.

Q20. Enlist different types of constructors available in Kotlin?

There are two types of constructors in Kotlin:

  • Primary Constructor
  • Secondary Constructor

Primary Constructor It initializes the class and is declared at the class header. Surrounded by parenthesis, it can have optional parameters.

class className(valname: String,varid: Int) { // body of the class }

Secondary Constructor The Secondary constructor can be created one or more in class. It is created using the "constructor" keyword.

class className{ constructor(id: Int){ //code } constructor(name: String){ //code } }

Q21. What is Null Safety in Kotlin?

Kotlin is null safety that is, it eliminates the jeopardy of null reference from the code. NullPointerExceptions are thrown by the program at runtime and sometimes cause application failure or system crashes. In Kotlin, the type system differentiates between references that can hold null (nullable references) and those that cannot (non-null references).

var c: String = "abc"
c = null // Null exception error cause the String cannot hold null.
you can add "?" to the type to decalre a nullable variable
var c: String? = "abc"
c= null // ok

Q22. What are high order functions in Kotlin?

Kotlin supports a higher-order function, that is functions can be passed as an argument to other functions or functions can be returned as a value by a function. It is possible because Kotlin functions can be stored in variables and data structures, passed as arguments to, and returned from other higher-order functions.

Functions can be declared as Lambda statements and can be passed or returned.
      // lambda expression 
var lambda = {println("higher order function") } 
      // higher-order function 
fun higherfunc( lmbd: () -> Unit ) {    // accepting lambda as parameter 
   //statemnts
} 
fun main(args: Array) { 
     //invoke higher-order function 
    higherfunc(lambda)       // passing lambda as parameter 
}  

Q23. What is use of data class in Kotlin?

A data class is a concept to represent, encapsulate, and move data around. A data class has fields as data and the getter & setter method for accessing the data. A data class in Kotlin introduces the "data" keyword and it automatically creates getter and setter properties when we declare data.

data class User(var name: String, var age: Int) // A data class in Kotlin

Getter and Setter property are automatically declared for var name and var age. data class also implements toString(), equals(), and hashcode() functions automatically. Along with it, it creates a function for every property (destructing declarations) and copy function for copying classes.

Q24. What is the Elvis Operator in Kotlin?

As you may know, Kotlin removes the dreaded NULL POINTER error. It is possible because of the Elvis operator. It receives two inputs and returns the first one if it is non-null or the second one.

The syntax of the Elvis operator is ?:
fun elvis(arg : String?) {	   
val value = arg ?: " "	   
}

In the above code, value is assigned with arg if it is non-null or it is assigned with empty space(" "). In a sense, it is a variant of ternary operator. Elvis operator in conjunction with safe call operator(?.) can be used to access nullable properties or methods. However, the resulting type will be nullable.

Q25. What is init block in Kotlin?

init block is a group of code declared with init operator, which is executed as soon as the class gets instantiated. It acts as a constructor and the block is executed every time the class gets instantiated.

init{
        print("Class instance is initialized.") //gets executed when the object is created.
    }

However, the priority for the init block is less than the primary constructor. So, if there is a primary constructor in a class, it gets executed first and then the init block. A class can have multiple init blocks in it.

About Author :

  • Author of Kotlin Interview Questions

    OM Prakash

    OM Prakash is Senior Android developer from new Delhi, India. He have rich experience in creating mobiles apps in Android, Ionic, Kotlin, Java. He loves listening old song and watching bolywood movies.

Leave A Comment :

Valid name is required.

Valid name is required.

Valid email id is required.