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 11. 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 12. 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 13. 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 14. 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 15. 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
 

Most helpful rated by users:

©2024 WithoutBook