Prepare Interview

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address

Kotlin Interview Questions and Answers

Test your skills through the online practice test: Kotlin Quiz Online Practice Test

Related differences

Java vs Kotlin

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 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 10. 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
 

Most helpful rated by users:

©2024 WithoutBook