Prepare Interview

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address
Withoutbook LIVE Mock Interviews
Test your skills through the online practice test: Kotlin Quiz Online Practice Test

Freshers / Beginner level questions & answers

Ques 1. What is Kotlin?

Kotlin is an open-source, general-purpose, statically typed programming language. It is JVM-based and may be used in all projects where Java is currently used.

It may be used to create Android apps, server-side apps, and a variety of other applications. It is an improved version of Java and is completely interoperable with it. We can even mix Kotlin and Java in the same project.

It blends Object Oriented Programming (OOPs) and functional programming in a platform that is unlimited, self-contained, and unique. It also enables functional twinning using microcodes. 

Is it helpful? Add Comment View Comments
 

Ques 2. Who has created Kotlin?

The JetBrains team created Kotlin. The language was initially launched in February 2016 after a project began in 2010 to develop it. The Apache 2.0 license was used to create Kotlin. 

Is it helpful? Add Comment View Comments
 

Ques 3. Tell some good features about Kotlin?

  • Programs written in Kotlin do not require semicolons. This makes the code more readable and easy to understand.
  • This language enables the interchange and usage of Java in a variety of ways.
  • Furthermore, code written in Java and Kotlin can coexist in the same project.
  • The type system of Kotlin is designed to eliminate NullPointerException from code.
  • Writing new code in Kotlin will take you less time.
  • Kotlin code is even easier to deploy and manage at scale.

Is it helpful? Add Comment View Comments
 

Ques 4. Tell me about the top features of Kotlin.

  • Compact code: Kotlin is an OOPs-based programming language with code lines that may be reduced by up to 40% when compared to Java, making it an excellent choice for software development.
  • Open Source: Kotlin for Android is open-source and uses the JVM to combine the benefits of OOPs and functional programming.
  • Simple Language: When working with Kotlin, compiling the code is simple, resulting in improved performance for Android development. It also explains which types of data functions can be used throughout the code.
  • High number of extensions: Without modifying the code, Kotlin may support a variety of extension functions. It aids developers in making existing code more appealing and wonderful.
  • Full Java Interoperability: Java code can utilize Kotlin code, and Kotlin code can use Java code. So, if you're familiar with OOPS programming, switching to Kotlin development is simple. Also, if there are any Java-based applications, they can be used with Kotlin's environment.
  • Smart Cast: Smart casting is a technique that reduces the cost of an application while also improving its speed and performance. It uses typecasting or immutable data to manage the efficiency of programming. This technique is supported by Kotlin.
  • Low Learning Curve: Kotlin is preferred by businesses due to its low adoption cost. Most significantly, it is simple for developers to learn, especially if they have programming experience.

Is it helpful? Add Comment View Comments
 

Ques 5. What are the various data types available in Kotlin? Explain them.

Primitive data types are the most basic data types in Kotlin, and all others are reference types like array and string. Kotlin contains all data types as objects. Following are the different data types available in Kotlin:

Integer Data Type -

Data TypeSpace Required
byte8 bits
short16 bits
int32 bits
long64 bits

Floating Point Data Type - 

Data TypeSpace Required
float32 bits
double64 bits

Boolean Data Type - 

True or false is the only bit of information represented by the Boolean data type. In Kotlin, the Boolean type is the same as in Java. 

Data TypeSpace Required
boolean1 bit

Character Data Type - 

Small letters (a-z), capital letters (A-Z), numerals (0-9), and other symbols are represented by the character data type.

Data TypeSpace Required
char8 bits

String Data Type -

Strings are represented in Kotlin by the type String. A string value is often a sequence of characters enclosed in double quotations ("). The space required in this case depends on the number of characters in the string.

Array Data Type -

The Array class in Kotlin is used to represent arrays. It has the get and set functions that, due to operator overloading conventions, can be used as  ‘[]’  as well. The space required by the array also depends on the number of elements it posses.

Is it helpful? Add Comment View Comments
 

Ques 6. How are variables declared in Kotlin? What are the different types of variables in Kotlin? Explain with examples.

Every variable in Kotlin must be declared before it can be used. An attempt to use a variable without declaring it results in a syntax error. The type of data you are authorised to put in the memory address is determined by the variable type declaration. The type of variable can be determined from the initialised value in the case of local variables.

For example,

var site = "interviewbit"

The above code declares a variable “site” of type String because the value with which the variable is initialised is a String.

  • Immutable Variables — Immutable variables are also known as read-only variables. They are declared using the val keyword. Once these variables have been declared, we cannot change their values.

The syntax is as follows :

val variableName = value

For example,

val sample = "interview"
sample = "interviewbit" // results in compile time error

The second line in the above code snippet would result in a compile-time error as expected.

Because it can be initialized with the value of a variable, an immutable variable is not a constant. It means that the value of an immutable variable does not need to be known at compile-time and that if it is defined inside a construct that is called several times, it can take on a different value with each function call. For example, 

var sample = "interview"
val newSample = sample // no compile time error

The above code snippet runs fine and does not produce any errors.

  • Mutable Variables - In a mutable variable, the value of the variable can be changed. We use the keyword “var” to declare such variables.

The syntax is as follows :

var variableName = value

For example,

var sample = "interview"
sample = "fun" // no compile time error

The above code snippet runs fine and does not produce any errors.

Is it helpful? Add Comment View Comments
 

Ques 7. What are data classes in Kotlin? Explain with a proper example.

The Data class is a simple class that holds data and provides typical functions. To declare a class as a data class, use the data keyword. 

Syntax:

data class className ( list_of_parameters)

The following functions are automatically derived by the compiler for the data classes:

  • equals() - The equals() function returns true if two objects have the identical contents. It operates similarly to \"==,\" although for Float and Double values it works differently.
  • hashCode() - The hashCode() function returns the object\'s hashcode value.
  • copy() - The copy() function is used to duplicate an object, changing only a few of its characteristics while leaving the rest unaltered.
  • toString() - This function returns a string containing all of the data class\'s parameters.

To ensure consistency, data classes must meet the following requirements:

  • At least one parameter is required for the primary constructor.
  • val or var must be used for all primary constructor parameters.
  • Abstract, open, sealed, or inner data classes are not possible.
  • Only interfaces may be implemented by data classes.

Example:

data class Sample(var input1 : Int, var input2 : Int)

The above code snippet creates a data class Sample with two parameters.

fun main(agrs: Array) {     
val temp = Sample(1, 2)
println(temp)

Here, we create an instance of the data class Sample and pass the parameters to it.

Output:-

Sample(input1=1, input2=2)

Is it helpful? Add Comment View Comments
 

Ques 8. Explain the concept of null safety in Kotlin.

Kotlin's type system aims to eradicate null references from the code. If a program throws NullPointerExceptions at runtime it might result in application failure or system crashes. If the Kotlin compiler finds a null reference it throws a NullPointerException.

The Kotlin type system distinguishes between references that can hold null (nullable references) and those that cannot (non-null references). Null cannot be stored in a String variable. We get a compiler error if we try to assign null to the variable. 

var a: String = "interview"
a = null // results in compilation error

If we want the above string to be able to hold null value as well, we can declare it of type nullable using the ‘?’ operator after the String keyword as follows :

var a: String? = "interview"
a = null // no compilation error

Kotlin provides Safe Call (?.), Elvis (?:) and Not Null Assertion (!!) operators which define what needs to be done in case of a null encounter. This makes the code more reliable and less prone to errors. Thus, Kotlin enforces null safety by having nullable, non-nullable type variables and the different operators to tackle null encounters.

Is it helpful? Add Comment View Comments
 

Ques 9. Explain the various methods to iterate over any data structure in Kotlin with examples.

Following are the different ways to iterate over any data structure in Kotlin :

  • For Loop - The for loop is used to scan any data structure that supplies an iterator in this case. It is not used in the same way as the for loop in other programming languages such as Java or C.

In Kotlin, the for loop has the following Syntax:

for(item in collection) {     
// code
}

Here, collection refers to the data structure to be iterated and item refers to each element of the data structure.

For example,

// KOTLIN
fun main(args: Array) {
var numbersArray = arrayOf(1,2,3,4,5,6,7,8,9,10)
for (num in numbersArray){
if(num % 2 == 0){
print("$num ")
}
}
}

Output -

2 4 6 8 10
  • While Loop - It is made up of a code block and a condition to be checked for each iteration. First, the while condition is assessed, and if it is true, the code within the block is executed. Because the condition is verified every time before entering the block, it repeats until the condition turns false. The while loop can be thought of as a series of if statements that are repeated.

The while loop\'s syntax is as follows:

while(condition) {         
// code
}

For example,

// KOTLIN
fun main(args: Array) {
var number = 1
while(number <= 5) {
println(number)
number++;
}
}

Output -

12345
  • Do While Loop - The condition is assessed after all of the statements inside the block have been executed. If the do-while condition is true, the code block is re-executed. As long as the expression evaluates to true, the code block execution procedure is repeated. The loop ends if the expression becomes false, and control is passed to the sentence following the do-while loop. Because it verifies the condition after the block is executed, it\'s also known as a post-test loop.

The do-while loop\'s syntax is as follows:

do {     
// code
} while(condition)

For example,

// KOTLIN
fun main(args: Array) {
var number = 4
var sum = 0
do {
sum += number
number--
} while(number > 0)
println("Sum of first four natural numbers is $sum")
}

Output -

Sum of first four natural numbers is 10

Is it helpful? Add Comment View Comments
 

Ques 10. How can you concatenate two strings in Kotlin?

Following are the different ways by which we can concatenate two strings in Kotlin:

Using String Interpolation:- We use the technique of string interpolation to concatenate the two strings. Basically, we substitute the strings in place of their placeholders in the initialisation of the third string.

val s1 = "Without"
val s2 = "Book"
val s3 = "$s1 $s2" // stores "Without Book"

Using the + or plus() operator:- We use the ‘+’ operator to concatenate the two strings and store them in a third variable.

val s1 = "Without"
val s2 = "Book"
val s3 = s1 + s2 // stores "WithoutBook"
val s4 = s1.plus(s2) // stores "WithoutBook"

Using StringBuilder:- We concatenate two strings using the StringBuilder object. First, we append the first string and then the second string. 

val s1 = "Without"
val s2 = "Book"
val s3 =  StringBuilder()   
s3.append(s1).append(s2)
val s4 = s3.toString() // stores "WithoutBook"

Is it helpful? Add Comment View Comments
 

Ques 11. What’s the Target Platform of Kotlin? How is Kotlin-Java interoperability possible?

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.

Is it helpful? Add Comment View Comments
 

Intermediate / 1 to 5 years experienced level questions & answers

Ques 12. Explain Safe call, Elvis and Not Null Assertion operator in the context of Kotlin.

Safe Call operator ( ?. ) -  Null comparisons are trivial, but the number of nested if-else expressions can be exhausting. So, in Kotlin, there\'s a Safe call operator,?, that simplifies things by only doing an action when a specified reference holds a non-null value. It allows us to use a single expression to perform both a null check and a method call.

For example,

The following expression in Kotlin

name?.toLowerCase() 

is equivalent to the following

if(name != null)    
name.toLowerCase()
else
null

Elvis Operator ( ?: ) - When the original variable is null, the Elvis operator is used to return a non-null value or a default value. In other words, the elvis operator returns the left expression if it is not null, otherwise, it yields the right expression. Only if the left-hand side expression is null is the right-hand side evaluated. 

For example,

The following expression in Kotlin

val sample1 = sample2 ?: "Undefined"

is equivalent to the following

val sample1 = if(sample2 != null)        
sample2
else 
"Undefined"

Furthermore, on the right side of the Elvis operator, we may use throw and return expressions, which is particularly handy in functions. As a result, instead of returning a default value on the right side of the Elvis operator, we can throw an exception. For example,

val sample1 = sample2 ?: throw IllegalArgumentException("Invalid")

Not Null Assertion Operator ( !! ) - If the value is null, the not null assertion (!!) operator changes it to a non-null type and throws an exception.

Anyone who wants a NullPointerException can ask for it explicitly with this operator.

For example,

// KOTLIN
fun main(args: Array) {
var sample : String? = null
str!!.length
}

The above code snippet gives the following output:-

Exception in thread "main" kotlin.KotlinNullPointerException

Is it helpful? Add Comment View Comments
 

Ques 13. Differentiate between Kotlin and Java.

Following are the differences between Kotlin and Java:

BasisKotlinJava
Null SafetyBy default, all sorts of variables in Kotlin are non-nullable (that is, we can\'t assign null values to any variables or objects). Kotlin code will fail to build if we try to assign or return null values. If we absolutely want a null value for a variable, we can declare it as follows: value num: Int? = null NullPointerExceptions are a big source of annoyance for Java developers. Users can assign null to any variable, however, when accessing an object reference with a null value, a null pointer exception is thrown, which the user must manage.
Coroutines Support We can perform long-running expensive tasks in several threads in Kotlin, but we also have coroutines support, which halt execution at a given moment without blocking threads while doing long-running demanding operations.The corresponding thread in Java will be blocked anytime we launch a long-running network I/0 or CPU-intensive task. Android is a single-threaded operating system by default. Java allows you to create and execute numerous threads in the background, but managing them is a difficult operation.
Data Classes If we need to have data-holding classes in Kotlin, we may define a class with the keyword \"data\" in the class declaration, and the compiler will take care of everything, including constructing constructors, getter, and setter methods for various fields.Let\'s say we need a class in Java that only holds data and nothing else. Constructors, variables to store data, getter and setter methods, hashcode(), function toString(), and equals() functions are all required to be written explicitly by the developer.
Functional ProgrammingKotlin is procedural and functional programming (a programming paradigm where we aim to bind everything in functional units) language that has numerous useful features such as lambda expressions, operator overloading, higher-order functions, and lazy evaluation, among others.Java does not allow functional programming until Java 8, however it does support a subset of Java 8 features when developing Android apps.
Extension FunctionsKotlin gives developers the ability to add new functionality to an existing class. By prefixing the name of a class to the name of the new function, we can build extended functions.In Java, we must create a new class and inherit the parent class if we want to enhance the functionality of an existing class. As a result, Java does not have any extension functions.
Data Type Inference We don\'t have to declare the type of each variable based on the assignment it will handle in Kotlin. We can specify explicitly if we want to.When declaring variables in Java, we must declare the type of each variable explicitly.
Smart CastingSmart casts in Kotlin will take care of these casting checks with the keyword \"is-checks,\" which checks for immutable values and conducts implicit casting.We must examine the type of variables in Java and cast them appropriately for our operation.
Checked ExceptionsWe don\'t have checked exceptions in Kotlin. As a result, developers do not need to declare or catch exceptions, which has both benefits and drawbacks.We have checked exceptions support in Java, which enables developers to declare and catch exceptions, resulting in more robust code with better error handling.

Is it helpful? Add Comment View Comments
 

Ques 14. What are the different types of constructors available in Kotlin? Explain them with proper examples.

  • Primary Constructor  - This type of constructor is initialised in the class header and is provided after the class name. It is declared using the “constructor” keyword. Parameters are optional in this type of constructor. For example,
class Sample constructor(val a: Int, val b: Int) {   
// code
}

If no annotations or access modifiers are provided, the constructor keyword can be omitted. The initialization code can be placed in a separate initializer block prefixed with the init keyword because the primary constructor cannot contain any code. 

For example, 

// KOTLIN
fun main(args: Array) {
val s1 = Sample(1, 2)
}
class Sample(a : Int , b: Int) {
val p: Int
var q: Int
// initializer block
init {
p = a
q = b
println("The first parameter value is : $p")
println(\"The second parameter value is : $q\")
}
}

Output:-

The first parameter value is: 1
The second parameter value is: 2

Explanation - The values 1 and 2 are supplied to the constructor arguments a and b when the object s1 is created for the class Sample. In the class p and q, two attributes are specified. The initializer block is called when an object is created, and it not only sets up the attributes but also prints them to the standard output.

  • Secondary Constructor - Secondary constructors allow for the initialization of variables as well as the addition of logic to the class. They have the constructor keyword prefixed to them. For example,
// KOTLIN
fun main(args: Array) {
val s1 = Sample(1, 2)
}
class Sample {
constructor(a: Int, b: Int) {
println("The first parameter value is : $p")
println("The second parameter value is : $q")
}
}

Output:-

The first parameter value is: 1
The second parameter value is: 2

The compiler determines which secondary constructor will be called based on the inputs provided. We don't specify which constructor to use in the above program, so the compiler chooses for us.

In Kotlin, a class can contain one or more secondary constructors and at most one primary constructor. The primary constructor initializes the class, while the secondary constructor initialises the class and adds some additional logic.

Is it helpful? Add Comment View Comments
 

Ques 15. Differentiate between open and public keywords in Kotlin.

The keyword “open” refers to the term "open for expansion". The open annotation on a class is the polar opposite of the final annotation in Java: it allows others to inherit from it. By default, a class cannot be inherited in Kotlin. In Kotlin, an open method signifies that it can be overridden, whereas it cannot be by default. Instead, any methods in Java can be overridden by default.

In Kotlin, all the classes are final by default. If no visibility modifier is specified, the public is used by default, which means our declarations will be accessible everywhere inside the program.

Is it helpful? Add Comment View Comments
 

Ques 16. Explain about the “when” keyword in the context of Kotlin.

The “when” keyword is used in Kotlin to substitute the switch operator in other languages such as Java. When a certain condition is met, a specific block of code must be run. Inside the when expression, it compares all of the branches one by one until a match is discovered. After finding the first match, it proceeds to the conclusion of the when block and executes the code immediately following the when block. We do not need a break statement at the end of each case, unlike switch cases in Java or any other programming language.

For example,

// KOTLIN
fun main(args: Array) {
var temp = "Interview"
when(temp) {
"Interview" -> println("Without Book is the solution.")
"Job" -> println("Interview is the solution.")
"Success" -> println("Hard Work is the solution.")
}
}

Output:-

Without Book is the solution.

Explanation:- In the above code, the variable temp has the value “Interview”. The when condition matches for the exact value as that of temp’s and executes the corresponding code statements. Thus, “Without Book is the solution” is printed.

Is it helpful? Add Comment View Comments
 

Experienced / Expert level questions & answers

Ques 17. What do you understand about function extension in the context of Kotlin? Explain.

In Kotlin, we can add or delete method functionality using extensions, even without inheriting or altering them. Extensions are statistically resolved. It provides a callable function that may be invoked with a dot operation, rather than altering the existing class.

Function Extension - Kotlin allows users to specify a method outside of the main class via function extension. We\'ll see how the extension is implemented at the functional level in the following example:

// KOTLIN
class Sample {
var str : String = "null"
fun printStr() {
print(str)
}
}
fun main(args: Array) {
var a = Sample()
a.str = "Without"
var b = Sample()
b.str = "Book"
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:-

Without Book

Is it helpful? Add Comment View Comments
 

Ques 18. What do you understand about Companion Object in the context of Kotlin?

In some languages, such as Java, the static keyword is used to declare class members and utilise them without creating an object, i.e. by simply calling them by their class name. In Kotlin, there is nothing called the “static” keyword. So, if we want to achieve the functionality of static member functions, we use the companion objects. This is also referred to as Object Extension. 

We must use the companion keyword in front of the object definition to construct a companion object.

// Syntax in KOTLIN
class CompanionClass {
companion object CompanionObjectName {
// code
}
}
val obj = CompanionClass.CompanionObjectName

We can also remove the CompanionObject name and replace it with the term companion, resulting in the companion object\'s default name being Companion, as shown below:

// KOTLIN
class CompanionClass {
companion object {
// code
}
}
val obj = CompanionClass.Companion

All the required static member functions and member variables can be kept inside the companion object created. For example,

class Sample {   
companion object Test {
var a: Int = 1
fun testFunction() = println("Companion Object’s Member function called.")
}
}
fun main(args: Array) {
println(Sample.a)
Sample.testFunction()
}

Output:-

1Companion Object’s Member function called.

Is it helpful? Add Comment View Comments
 

Ques 19. What are the advantages of Kotlin over Java?

Following are the advantages of Kotlin over Java:

  • Data class: In Java, you must create getters and setters for each object, as well as properly write hashCode (or allow the IDE to build it for you, which you must do every time you update the class), toString, and equals. Alternatively, you could utilize lombok, but that has its own set of issues. In Kotlin, data classes take care of everything.
  • Patterns of getter and setter: In Java, for each variable, you use it for, rewrite the getter and setter methods. You don't have to write getter and setter in kotlin, and if you must, custom getter and setter take a lot less typing. There are additional delegates for identical getters and setters.
  • Extension Functions: In Java, there is no support for extension functions. Kotlin on the other hand provides support for extension functions which makes the code more clear and cleaner.
  • Support for one common codebase: You may extract one common codebase that will target all of them at the same time using the Kotlin Multi-Platform framework.
  • Support for Null Safety: Kotlin has built-in null safety support, which is a lifesaver, especially on Android, which is full of old Java-style APIs.
  • Less prone to errors: There is less space for error because it is more concise and expressive than Java.

Is it helpful? Add Comment View Comments
 

Ques 20. Which one is better to use - val mutableList or var immutableList in the context of Kotlin?

The program's design clarity is improved by using mutable and immutable lists. This is done to have the developer think about and clarify the collection's purpose.

We use a mutable list if the collection will alter as part of the design. On the other hand, we use an immutable list if the model is only meant to be viewed.

Val and var serve a distinct purpose than immutable and mutable lists. The val and var keywords specify how a variable's value/reference should be handled. We use var when the value or reference of a variable can be altered at any moment. On the other hand, we use val when a variable's value/reference can only be assigned once and cannot be modified later in the execution.

Immutable lists are frequently preferred for a variety of reasons:

  • They promote functional programming, in which state is passed on to the next function, which constructs a new state based on it, rather than being altered. This is evident in Kotlin collection methods like map, filter, reduce, and so forth.
  • It's often easier to understand and debug software that doesn't have any side effects (you can be sure that the value of an object will always be the one at its definition).
  • Because no write access is required in multi-threaded systems, immutable resources cannot induce race conditions.

However, there are some disadvantages of using immutable lists as well. They are as follows :

  • Copying large collections simply to add/remove a single piece is very expensive.
  • When you need to alter single fields frequently, immutability can make the code more difficult. Data classes in Kotlin provide a built-in copy() method that allows you to clone an instance while changing only part of the fields' values.

Is it helpful? Add Comment View Comments
 

Ques 21. What do you understand about lateinit in Kotlin? When would you consider using it?

lateinit is an abbreviation for late initiation. If you don\'t want to initialize a variable in the constructor and instead want to do it later, and you can guarantee the initialization before using it, use the lateinit keyword to declare that variable. It won\'t start allocating memory until it\'s been initialized. Lateinit cannot be used for primitive type attributes like Int, Long, and so on. Because the lateinit variable will be initialized later, you cannot use val. When a lateinit property is accessed before it has been initialized, a special exception is thrown that explicitly identifies the property and the fact that it hasn\'t been initialized.

For example,

// KOTLIN
lateinit var test: Stringfun testFunction() {
test = "Interview"
println("The length of string is "+test.length)
test = "Book"
}

When the testFunction is called, we get the following output:-

9 

There are a few scenarios in which this is particularly useful, for example:

  • Variables that are initialized in lifecycle methods in Android;
  • Using Dagger for DI: injected class variables are initialized outside of the constructor and independently;
  • Setup for unit tests: in a @Before - annotated function, test environment variables are initialized;
  • Annotations in Spring Boot (for example, @Autowired).

Is it helpful? Add Comment View Comments
 

Ques 22. Explain lazy initialization in the context of Kotlin.

There are some classes whose object initialization is so time-consuming that it causes the entire class creation process to be delayed. Lazy initialisation helps in such problems. When we declare an object using lazy initialisation, the object is initialised only once when the object is used. If the object is not used throughout, the object is not initialised. This makes the code more efficient and faster. 

For example, let us imagine you have a SlowClass class and you require an object of that SlowClass in a different class called FastClass:

// KOTLIN
class FastClass {
private val slowObject: SlowClass = SlowClass()
}

We are generating a large object here, which will cause the development of the FastClass to be slow or delayed. There may be times where the SlowClass object isn\\\'t required. As a result, the lazy keyword can assist you in this situation:

class FastClass {   
private val slowObject: SlowClass by lazy {
SlowClass()
}
}

For example,

// KOTLIN
class FastClass {
private val slowObject: SlowClass by lazy {
println("Slow Object initialised")
SlowClass()

fun access() {
println(slowObject)
}
}
fun main(args: Array) {
val fastClass = FastClass()
println("FastClass initialised")
fastClass.access()
fastClass.access()
}

Output:-

FastClass initialised 
Slow Object initialised 
SlowClass@2b12fkk7 
SlowClass@2b12fkk7

Explanation:- In the above code, we have instantiated an object of the SlowClass inside the class structure of the FastClass using lazy initialisation. The object of the SlowClass is generated only when it is accessed in the above code, that is, when we call the access() method of the FastClass object and the same object is present throughout the main() method.

Is it helpful? Add Comment View Comments
 

Ques 23. Differentiate between lateinit and lazy initialisation. Explain the cases when you should use lateinit and when you should use lazy initialisation.

lateinitlazy initialisation
The main purpose is to delay the initialisation to a later point in time.The main purpose is to initialise an object only when it is used at a later point in time. Also, a single copy of the object is maintained throughout the program. 
It\'s possible to initialise the object from anywhere in the program.Only the initializer lambda can be used to initialise it.
Multiple initializations are possible in this case.Only a single initialisation is possible in this case.
It\'s not thread-safe. In a multi-threaded system, it is up to the user to correctly initialise.Thread-safety is enabled by default, ensuring that the initializer is only called once.
It works only with var.It works only with val.
The isInitialized method is added to verify if the value has previously been initialised.It is impossible to uninitialize a property.
Properties of primitive types are not allowedAllowable on primitive type properties.

Is it helpful? Add Comment View Comments
 

Ques 24. What do you understand about coroutines in the context of Kotlin?

Unlike many other languages with equivalent capabilities, async and await are neither keywords nor part of Kotlin's standard library. JetBrains' kotlinx.coroutines library is a comprehensive library for coroutines. It includes a number of high-level coroutine-enabled primitives, such as launch and async. Kotlin Coroutines provide an API for writing asynchronous code in a sequential manner.

Coroutines are similar to thin threads. Coroutines are lightweight since they don't allocate new threads when they're created. Instead, they employ pre-defined thread pools as well as intelligent scheduling. The process of deciding which piece of work you will do next is known as scheduling. Coroutines can also be paused and resumed in the middle of their execution. This means you can have a long-term project that you can work on incrementally. You can pause it as many times as you want and continue it whenever you're ready.

Is it helpful? Add Comment View Comments
 

Ques 25. Explain scope functions in the context of Kotlin. What are the different types of Scope functions available in Kotlin?

The Kotlin standard library includes numerous functions that aid in the execution of a block of code within the context of an object. When you use a lambda expression to call these functions on an object, temporary scope is created. These functions are referred to as Scope functions. The object of these functions can be accessed without knowing its name. Scope functions make code more clear, legible, and succinct, which are key qualities of the Kotlin programming language.

Following are the different types of Scope functions available in Kotlin:-

  • let:- 
    Context object:   it 
    Return value:   lambda result
    The let function is frequently used for null safety calls. For null safety, use the safe call operator(?.) with ‘let'. It only runs the block with a non-null value.
  • apply:-
    Context object:  this
    Return value:   context object
    “Apply these to the object,” as the name suggests. It can be used to operate on receiver object members, primarily to initialise them.
  • with:-
    Context object:  this
    Return value:   lambda result
    When calling functions on context objects without supplying the lambda result, ‘with' is recommended.
  • run:-
    Context object:  this 
    Return value:   lambda result
    The ‘run' function is a combination of the ‘let' and ‘with' functions. When the object lambda involves both initialization and computation of the return value, this is the method to use. We can use run to make null safety calls as well as other calculations.
  • also:-
    Context object:  it
    Return value:   context object
    It's used when we need to do additional operations after the object members have been initialised.

Is it helpful? Add Comment View Comments
 

Ques 26. Explain suspend function in the context of Kotlin.

A function that may be started, halted, then resumed is known as a suspend function. One of the most important things to remember about the suspend functions is that they can only be invoked from another suspend function or from a coroutine. Suspending functions are merely standard Kotlin functions with the suspend modifier added, indicating that they can suspend coroutine execution without blocking the current thread. This means that the code you're looking at may pause execution when it calls a suspending function and restart execution at a later time. However, it makes no mention of what will happen to the present thread in the meantime.

Suspending functions can call any other ordinary functions, but another suspending function is required to suspend the execution. Because a suspending function cannot be called from a regular function, numerous coroutine builders are supplied, allowing you to call a suspending function from a non-suspending scope like launch, async, or runBlocking.

delay() function is an example of suspend function.

Is it helpful? Add Comment View Comments
 

Ques 27. What do you understand about sealed classes in Kotlin?

Kotlin introduces a crucial new form of class that isn't seen in Java. These are referred to as "sealed classes." Sealed classes, as the name implies, adhere to constrained or bounded class hierarchies. A sealed class is one that has a set of subclasses. When it is known ahead of time that a type will conform to one of the subclass types, it is employed. Type safety (that is, the compiler will validate types during compilation and throw an exception if a wrong type has been assigned to a variable) is ensured through sealed classes, which limit the types that can be matched at compile time rather than runtime.

Is it helpful? Add Comment View Comments
 

Ques 28. What do you understand about the backing field in Kotlin?

A backing field is an auto-generated field for any property that may only be used inside accessors (getter or setter) and will only be present if it utilizes the default implementation of at least one of the accessors, or if a custom accessor refers to it through the field identifier. This backing field is used to avoid an accessor's recursive call, which would result in a StackOverflowError.

Fields are not allowed in Kotlin classes. When employing custom accessors, however, it is occasionally required to have a backing field. Kotlin includes an automatic backing field for these purposes, which may be accessed by the field identifier.

For example,

var marks: Int = someValue       
get() = field
set(value) {
field = value
}

Explanation:-  Here the field identifier acts as a reference to the property “marks” value in the get() and set() method. So, whenever we call the get(), we get the field’s value returned. Similarly, whenever we call the set(), we set the “marks” property value to “value”.

Is it helpful? Add Comment View Comments
 

Ques 29. Differentiate between launch / join and async / await in Kotlin.

launch / join:-

The launch command is used to start and stop a coroutine. It's as though a new thread has been started. If the code inside the launch throws an exception, it's considered as an uncaught exception in a thread, which is typically written to stderr in backend JVM programs and crashes Android applications. Join is used to wait for the launched coroutine to complete before propagating its exception. A crashed child coroutine, on the other hand, cancels its parent with the matching exception.

async / await:-

The async keyword is used to initiate a coroutine that computes a result. You must use await on the result, which is represented by an instance of Deferred. Uncaught exceptions in async code are held in the resultant Deferred and are not transmitted anywhere else. They are not executed until processed.

Is it helpful? Add Comment View Comments
 

Ques 30. What are some of the disadvantages of Kotlin?

Following are some of the disadvantages of Kotlin:

  • In Kotlin, there are a few keywords that have non-obvious meanings: internal, crossinline, expect, reified, sealed, inner, open. Java has none of these.
  • Checked exceptions are likewise absent in Kotlin. Although checked exceptions have become less prominent, many programmers believe them to be an effective technique to ensure that their code is stable.
  • A lot of what happens in Kotlin is hidden. You can almost always trace the logic of a program in Java. When it comes to bug hunting, this can be really useful. If you define a data class in Kotlin, getters, setters, equality testing, tostring, and hashcode are automatically added for you.
  • Learning resources are limited. The number of developers who are moving to Kotlin is growing, yet there is a small developer community accessible to help them understand the language or address problems during development.
  • Kotlin has variable compilation speed. In some situations, Kotlin outperforms Java, particularly when executing incremental builds. However, we must remember that when it comes to clean builds, Java is the clear winner.

Is it helpful? Add Comment View Comments
 

Most helpful rated by users:

Related differences

Java vs Kotlin

Related interview subjects

Java 15 interview questions and answers - Total 16 questions
Core Java interview questions and answers - Total 306 questions
Java Multithreading interview questions and answers - Total 30 questions
Apache Wicket interview questions and answers - Total 26 questions
JBoss interview questions and answers - Total 14 questions
Log4j interview questions and answers - Total 35 questions
Java Mail interview questions and answers - Total 27 questions
Java Applet interview questions and answers - Total 29 questions
Google Gson interview questions and answers - Total 8 questions
Java 21 interview questions and answers - Total 21 questions
Struts interview questions and answers - Total 84 questions
RMI interview questions and answers - Total 31 questions
Apache Camel interview questions and answers - Total 20 questions
Java Support interview questions and answers - Total 30 questions
JAXB interview questions and answers - Total 18 questions
JSP interview questions and answers - Total 49 questions
Java Concurrency interview questions and answers - Total 30 questions
J2EE interview questions and answers - Total 25 questions
JUnit interview questions and answers - Total 24 questions
Java OOPs interview questions and answers - Total 30 questions
Apache Tapestry interview questions and answers - Total 9 questions
JDBC interview questions and answers - Total 27 questions
Java 11 interview questions and answers - Total 24 questions
Java Garbage Collection interview questions and answers - Total 30 questions
Spring Framework interview questions and answers - Total 53 questions
Java Swing interview questions and answers - Total 27 questions
Java Design Patterns interview questions and answers - Total 15 questions
JPA interview questions and answers - Total 41 questions
Hibernate interview questions and answers - Total 52 questions
JMS interview questions and answers - Total 64 questions
JSF interview questions and answers - Total 24 questions
Java 8 interview questions and answers - Total 30 questions
Java 17 interview questions and answers - Total 20 questions
Servlets interview questions and answers - Total 34 questions
EJB interview questions and answers - Total 80 questions
Java Beans interview questions and answers - Total 57 questions
Java Exception Handling interview questions and answers - Total 30 questions
Spring Boot interview questions and answers - Total 50 questions
Kotlin interview questions and answers - Total 30 questions

All interview subjects

ASP interview questions and answers - Total 82 questions
C# interview questions and answers - Total 41 questions
LINQ interview questions and answers - Total 20 questions
ASP .NET interview questions and answers - Total 31 questions
Microsoft .NET interview questions and answers - Total 60 questions
Artificial Intelligence (AI) interview questions and answers - Total 47 questions
Machine Learning interview questions and answers - Total 30 questions
NLP interview questions and answers - Total 30 questions
ChatGPT interview questions and answers - Total 20 questions
OpenCV interview questions and answers - Total 36 questions
TensorFlow interview questions and answers - Total 30 questions
COBOL interview questions and answers - Total 50 questions
R Language interview questions and answers - Total 30 questions
Python Coding interview questions and answers - Total 20 questions
Scala interview questions and answers - Total 48 questions
Swift interview questions and answers - Total 49 questions
Golang interview questions and answers - Total 30 questions
Embedded C interview questions and answers - Total 30 questions
C++ interview questions and answers - Total 142 questions
VBA interview questions and answers - Total 30 questions
CCNA interview questions and answers - Total 40 questions
Snowflake interview questions and answers - Total 30 questions
Oracle APEX interview questions and answers - Total 23 questions
AWS interview questions and answers - Total 87 questions
Azure Data Factory interview questions and answers - Total 30 questions
Microsoft Azure interview questions and answers - Total 35 questions
OpenStack interview questions and answers - Total 30 questions
ServiceNow interview questions and answers - Total 30 questions
GDPR interview questions and answers - Total 30 questions
CCPA interview questions and answers - Total 20 questions
HITRUST interview questions and answers - Total 20 questions
LGPD interview questions and answers - Total 20 questions
PDPA interview questions and answers - Total 20 questions
OSHA interview questions and answers - Total 20 questions
HIPPA interview questions and answers - Total 20 questions
PHIPA interview questions and answers - Total 20 questions
FERPA interview questions and answers - Total 20 questions
DPDP interview questions and answers - Total 30 questions
PIPEDA interview questions and answers - Total 20 questions
Operating System interview questions and answers - Total 22 questions
MS Word interview questions and answers - Total 50 questions
Tips and Tricks interview questions and answers - Total 30 questions
PoowerPoint interview questions and answers - Total 50 questions
Data Structures interview questions and answers - Total 49 questions
Computer Networking interview questions and answers - Total 65 questions
Microsoft Excel interview questions and answers - Total 37 questions
Computer Basics interview questions and answers - Total 62 questions
Computer Science interview questions and answers - Total 50 questions
Python Pandas interview questions and answers - Total 48 questions
Python Matplotlib interview questions and answers - Total 30 questions
Django interview questions and answers - Total 50 questions
Pandas interview questions and answers - Total 30 questions
Deep Learning interview questions and answers - Total 29 questions
PySpark interview questions and answers - Total 30 questions
Flask interview questions and answers - Total 40 questions
PyTorch interview questions and answers - Total 25 questions
Data Science interview questions and answers - Total 23 questions
SciPy interview questions and answers - Total 30 questions
Generative AI interview questions and answers - Total 30 questions
NumPy interview questions and answers - Total 30 questions
Python interview questions and answers - Total 106 questions
Oracle interview questions and answers - Total 34 questions
MongoDB interview questions and answers - Total 27 questions
Entity Framework interview questions and answers - Total 46 questions
AWS DynamoDB interview questions and answers - Total 46 questions
MySQL interview questions and answers - Total 108 questions
Data Modeling interview questions and answers - Total 30 questions
Redis Cache interview questions and answers - Total 20 questions
DBMS interview questions and answers - Total 73 questions
MariaDB interview questions and answers - Total 40 questions
Apache Hive interview questions and answers - Total 30 questions
SSIS interview questions and answers - Total 30 questions
PostgreSQL interview questions and answers - Total 30 questions
SQL Query interview questions and answers - Total 70 questions
Teradata interview questions and answers - Total 20 questions
SQLite interview questions and answers - Total 53 questions
Cassandra interview questions and answers - Total 25 questions
Neo4j interview questions and answers - Total 44 questions
MSSQL interview questions and answers - Total 50 questions
OrientDB interview questions and answers - Total 46 questions
SQL interview questions and answers - Total 152 questions
Data Warehouse interview questions and answers - Total 20 questions
IBM DB2 interview questions and answers - Total 40 questions
Data Mining interview questions and answers - Total 30 questions
Elasticsearch interview questions and answers - Total 61 questions
VLSI interview questions and answers - Total 30 questions
Digital Electronics interview questions and answers - Total 38 questions
Software Engineering interview questions and answers - Total 27 questions
MATLAB interview questions and answers - Total 25 questions
Civil Engineering interview questions and answers - Total 30 questions
Electrical Machines interview questions and answers - Total 29 questions
Data Engineer interview questions and answers - Total 30 questions
AutoCAD interview questions and answers - Total 30 questions
Robotics interview questions and answers - Total 28 questions
Power System interview questions and answers - Total 28 questions
Electrical Engineering interview questions and answers - Total 30 questions
Verilog interview questions and answers - Total 30 questions
TIBCO interview questions and answers - Total 30 questions
Informatica interview questions and answers - Total 48 questions
Oracle CXUnity interview questions and answers - Total 29 questions
Web Services interview questions and answers - Total 10 questions
Salesforce Lightning interview questions and answers - Total 30 questions
Power BI interview questions and answers - Total 24 questions
IBM Integration Bus interview questions and answers - Total 30 questions
OIC interview questions and answers - Total 30 questions
Dell Boomi interview questions and answers - Total 30 questions
Web API interview questions and answers - Total 31 questions
Salesforce interview questions and answers - Total 57 questions
IBM DataStage interview questions and answers - Total 20 questions
Talend interview questions and answers - Total 34 questions
Java 15 interview questions and answers - Total 16 questions
Core Java interview questions and answers - Total 306 questions
Java Multithreading interview questions and answers - Total 30 questions
Apache Wicket interview questions and answers - Total 26 questions
JBoss interview questions and answers - Total 14 questions
Log4j interview questions and answers - Total 35 questions
Java Mail interview questions and answers - Total 27 questions
Java Applet interview questions and answers - Total 29 questions
Google Gson interview questions and answers - Total 8 questions
Java 21 interview questions and answers - Total 21 questions
Struts interview questions and answers - Total 84 questions
RMI interview questions and answers - Total 31 questions
Apache Camel interview questions and answers - Total 20 questions
Java Support interview questions and answers - Total 30 questions
JAXB interview questions and answers - Total 18 questions
JSP interview questions and answers - Total 49 questions
Java Concurrency interview questions and answers - Total 30 questions
J2EE interview questions and answers - Total 25 questions
JUnit interview questions and answers - Total 24 questions
Java OOPs interview questions and answers - Total 30 questions
Apache Tapestry interview questions and answers - Total 9 questions
JDBC interview questions and answers - Total 27 questions
Java 11 interview questions and answers - Total 24 questions
Java Garbage Collection interview questions and answers - Total 30 questions
Spring Framework interview questions and answers - Total 53 questions
Java Swing interview questions and answers - Total 27 questions
Java Design Patterns interview questions and answers - Total 15 questions
JPA interview questions and answers - Total 41 questions
Hibernate interview questions and answers - Total 52 questions
JMS interview questions and answers - Total 64 questions
JSF interview questions and answers - Total 24 questions
Java 8 interview questions and answers - Total 30 questions
Java 17 interview questions and answers - Total 20 questions
Servlets interview questions and answers - Total 34 questions
EJB interview questions and answers - Total 80 questions
Java Beans interview questions and answers - Total 57 questions
Java Exception Handling interview questions and answers - Total 30 questions
Spring Boot interview questions and answers - Total 50 questions
Kotlin interview questions and answers - Total 30 questions
Pega interview questions and answers - Total 30 questions
ITIL interview questions and answers - Total 25 questions
Finance interview questions and answers - Total 30 questions
SAP MM interview questions and answers - Total 30 questions
JIRA interview questions and answers - Total 30 questions
SAP ABAP interview questions and answers - Total 24 questions
SCCM interview questions and answers - Total 30 questions
Tally interview questions and answers - Total 30 questions
iOS interview questions and answers - Total 52 questions
Ionic interview questions and answers - Total 32 questions
Android interview questions and answers - Total 14 questions
Mobile Computing interview questions and answers - Total 20 questions
Xamarin interview questions and answers - Total 31 questions
DevOps interview questions and answers - Total 45 questions
Algorithm interview questions and answers - Total 50 questions
Splunk interview questions and answers - Total 30 questions
Accounting interview questions and answers - Total 30 questions
Business Analyst interview questions and answers - Total 40 questions
SSB interview questions and answers - Total 30 questions
OSPF interview questions and answers - Total 30 questions
Sqoop interview questions and answers - Total 30 questions
JSON interview questions and answers - Total 16 questions
Accounts Payable interview questions and answers - Total 30 questions
IoT interview questions and answers - Total 30 questions
Computer Graphics interview questions and answers - Total 25 questions
Insurance interview questions and answers - Total 30 questions
Scrum Master interview questions and answers - Total 30 questions
XML interview questions and answers - Total 25 questions
Bitcoin interview questions and answers - Total 30 questions
Laravel interview questions and answers - Total 30 questions
GraphQL interview questions and answers - Total 32 questions
Active Directory interview questions and answers - Total 30 questions
Microservices interview questions and answers - Total 30 questions
Adobe AEM interview questions and answers - Total 50 questions
Tableau interview questions and answers - Total 20 questions
Apache Kafka interview questions and answers - Total 38 questions
Kubernetes interview questions and answers - Total 30 questions
OOPs interview questions and answers - Total 30 questions
PHP OOPs interview questions and answers - Total 30 questions
Desktop Support interview questions and answers - Total 30 questions
Fashion Designer interview questions and answers - Total 20 questions
IAS interview questions and answers - Total 56 questions
Nursing interview questions and answers - Total 40 questions
Dynamic Programming interview questions and answers - Total 30 questions
Linked List interview questions and answers - Total 15 questions
CICS interview questions and answers - Total 30 questions
SharePoint interview questions and answers - Total 28 questions
Yoga Teachers Training interview questions and answers - Total 30 questions
Behavioral interview questions and answers - Total 29 questions
Language in C interview questions and answers - Total 80 questions
School Teachers interview questions and answers - Total 25 questions
Digital Marketing interview questions and answers - Total 40 questions
Statistics interview questions and answers - Total 30 questions
Apache Spark interview questions and answers - Total 24 questions
Full-Stack Developer interview questions and answers - Total 60 questions
VISA interview questions and answers - Total 30 questions
IIS interview questions and answers - Total 30 questions
System Design interview questions and answers - Total 30 questions
Cloud Computing interview questions and answers - Total 42 questions
Google Analytics interview questions and answers - Total 30 questions
ANT interview questions and answers - Total 10 questions
BPO interview questions and answers - Total 48 questions
SEO interview questions and answers - Total 51 questions
HR Questions interview questions and answers - Total 49 questions
Control System interview questions and answers - Total 28 questions
Agile Methodology interview questions and answers - Total 30 questions
Content Writer interview questions and answers - Total 30 questions
SAS interview questions and answers - Total 24 questions
REST API interview questions and answers - Total 52 questions
Blockchain interview questions and answers - Total 29 questions
Mainframe interview questions and answers - Total 20 questions
Checkpoint interview questions and answers - Total 20 questions
Hadoop interview questions and answers - Total 40 questions
Banking interview questions and answers - Total 20 questions
Technical Support interview questions and answers - Total 30 questions
Sales interview questions and answers - Total 30 questions
Chemistry interview questions and answers - Total 50 questions
Nature interview questions and answers - Total 20 questions
Docker interview questions and answers - Total 30 questions
Interview Tips interview questions and answers - Total 30 questions
SDLC interview questions and answers - Total 75 questions
RPA interview questions and answers - Total 26 questions
Cryptography interview questions and answers - Total 40 questions
College Teachers interview questions and answers - Total 30 questions
Memcached interview questions and answers - Total 28 questions
GIT interview questions and answers - Total 30 questions
Blue Prism interview questions and answers - Total 20 questions
JCL interview questions and answers - Total 20 questions
JavaScript interview questions and answers - Total 59 questions
Ajax interview questions and answers - Total 58 questions
Express.js interview questions and answers - Total 30 questions
Ansible interview questions and answers - Total 30 questions
ES6 interview questions and answers - Total 30 questions
Electron.js interview questions and answers - Total 24 questions
NodeJS interview questions and answers - Total 30 questions
RxJS interview questions and answers - Total 29 questions
jQuery interview questions and answers - Total 22 questions
ExtJS interview questions and answers - Total 50 questions
Vue.js interview questions and answers - Total 30 questions
Svelte.js interview questions and answers - Total 30 questions
Shell Scripting interview questions and answers - Total 50 questions
Next.js interview questions and answers - Total 30 questions
TypeScript interview questions and answers - Total 38 questions
Knockout JS interview questions and answers - Total 25 questions
Terraform interview questions and answers - Total 30 questions
PowerShell interview questions and answers - Total 27 questions
Ethical Hacking interview questions and answers - Total 40 questions
Cyber Security interview questions and answers - Total 50 questions
PII interview questions and answers - Total 30 questions
Data Protection Act interview questions and answers - Total 20 questions
BGP interview questions and answers - Total 30 questions
Tomcat interview questions and answers - Total 16 questions
Glassfish interview questions and answers - Total 8 questions
Ubuntu interview questions and answers - Total 30 questions
Linux interview questions and answers - Total 43 questions
Unix interview questions and answers - Total 105 questions
Weblogic interview questions and answers - Total 30 questions
QTP interview questions and answers - Total 44 questions
Cucumber interview questions and answers - Total 30 questions
TestNG interview questions and answers - Total 38 questions
Postman interview questions and answers - Total 30 questions
SDET interview questions and answers - Total 30 questions
Quality Assurance interview questions and answers - Total 56 questions
Mobile Testing interview questions and answers - Total 30 questions
Kali Linux interview questions and answers - Total 29 questions
UiPath interview questions and answers - Total 38 questions
Selenium interview questions and answers - Total 40 questions
API Testing interview questions and answers - Total 30 questions
Appium interview questions and answers - Total 30 questions
ETL Testing interview questions and answers - Total 20 questions
CSS interview questions and answers - Total 74 questions
Ruby On Rails interview questions and answers - Total 74 questions
Yii interview questions and answers - Total 30 questions
Angular interview questions and answers - Total 50 questions
PHP interview questions and answers - Total 27 questions
Oracle JET(OJET) interview questions and answers - Total 54 questions
Frontend Developer interview questions and answers - Total 30 questions
Zend Framework interview questions and answers - Total 24 questions
RichFaces interview questions and answers - Total 26 questions
HTML interview questions and answers - Total 27 questions
Flutter interview questions and answers - Total 25 questions
CakePHP interview questions and answers - Total 30 questions
React Native interview questions and answers - Total 26 questions
React interview questions and answers - Total 40 questions
Web Developer interview questions and answers - Total 50 questions
Angular JS interview questions and answers - Total 21 questions
Angular 8 interview questions and answers - Total 32 questions
Dojo interview questions and answers - Total 23 questions
Symfony interview questions and answers - Total 30 questions
GWT interview questions and answers - Total 27 questions
©2024 WithoutBook