![Koda School](/_next/image?url=%2Fimages%2Flogo.png&w=96&q=75)
KodaSchool
Learn To Code
Top 50 Kotlin Interview Questions and Answers
This article covers the most commonly asked Kotlin questions and answers in an interview.Additionally,it gives you a clear picture of what recruiters test in most software engineering interviews.
topics
Basics of Kotlin
- What is Kotlin, and why is it used?
Kotlin is a statically typed programming language that makes developers more efficient. For instance, compared to other programming languages, Kotlin enables you to be more precise and write fewer lines of code to achieve the same functions.
Why use Kotlin?
- Fewer lines of code that enable easier readability.
- Reduced crash rates.
- Kotlin is supported in Jetpack Libraries.
- Kotlin supports multiplatform development for android,iOS,web and backend.
- Kotlin is interoperable with Java.
- Kotlin has a less steep learning curve compared to other languages such as Java.
2.In Kotlin, how is a variable declared?
When using Kotlin, you declare a variable by first using the keyword val or var, then the variable's name.
3.What are the different types of variables in Kotlin?
There are different types of variables based on mutability and scope.
- Immutable variables include val that do not change.
- Mutable variables include var that can change.
- Local variables are usually declared within a function,block or inside another local scope.They are usually only accessible within that scope.
Example
fun greet() {
val message: String = "Good morning"
println(message)
}
- Member variables that are normally declared inside a class.They use either val or var.
Example
class Person {
var name: String = "John"
val birthYear: Int = 1998
}
4.Describe the distinction between val and var.
Val is an immutable variable that can be assigned only once while var is a mutable variable that can be assigned multiple times.
5.What is a Kotlin nullable type, and how is it declared?
In Kotlin,a type is nullable if it can hold null references.
For instance you can enable a string to be nullable by using ? operator
var b: String? = "abc" // can be set to null
b = null // ok
print(b)
6.How do you handle null values(null safety) in Kotlin?
You can handle null values in a number of ways including:
- Checking for nullable types using ? operator
var b: String? = "abc" // can be set to null
b = null // ok
print(b)
- Checking for null in conditions for instance
val l = if (b != null) b.length else -1
- Using Safe calls by utilizing the safe call operator ?.
val a = "Kotlin Program"
val b: String? = null
println(b?.length)
- Applying the Elvis operator
val l = b?.length ?: -1
- Using the not-null assertion operator(!!)
val l = b!!.length
- Use of Safe casts
Safe casts return null if the operation is not successful
val aInt: Int? = a as? Int
7.Describe Kotlin's type inference concept.
Type inference in Kotlin refers to the compiler's ability to automatically deduce the type of a variable or expression based on the context in which it is used instead of requiring explicit type declarations from the developer. This feature preserves type safety while simplifying the code.
8.What is Kotlin's Elvis operator?
An Elvis operator provides a concise way of handling null values and enhancing null safely by providing a non-null value when the expression evaluates to null.
9.Could you explain how to initialize an array with values in Kotlin?
An array can be initialized by using functions such as such as arrayOf(), arrayOfNulls() or emptyArray() or an Array constructor.
Example
val simpleArray = arrayOf(1, 2, 3)
println(simpleArray.joinToString())
10.In Kotlin, what is a data class?
A data class is designed to hold data.
data class Country(val name: String, val size: Int)
11.Show the difference between == and === in Kotlin?
== (Structural Equality) evaluates if two objects have the same value. It is equivalent to calling the equals() method.On the other hand,=== (Referential Equality) checks if two references point to the same object in memory.
12.What is the alternative name of a function literal?
A function literal is also known as a Lambda expression or simply lambda.
Functions and Lambda
13.In Kotlin, how do you define a function?
The fun keyword, the function name, parenthesis for any parameters, and the function body make up the fundamental syntax for defining a function. You have the option to define the function's return type.
Example
fun greet() {
println("Hello, World!")
}
14.What is an inline function?
An inline function eliminates the overhead associated with function calls by inserting its body directly into the locations where it is called. An inline function is declared with the inline keyword.
15.What is the purpose of Kotlin functions' default arguments?
Kotlin default arguments let programmers set a function parameter's default value. Consequently, when you call a function, the default value is used if the parameter is not given explicitly. However, if the function is called with arguments given, then those arguments are treated as parameters.
Example
fun test(
b: ByteArray,
off: Int = 0,
len: Int = b.size,
) { /*...*/ }
16.What are named arguments?
Named arguments are arguments assigned a name.For instance,you can name one or more of a function's arguments when calling it. This is handy when a function has numerous arguments and it is hard to associate a value with an argument.
Example
testnamedargurment(
"String!",
false,
upperCaseFirstLetter = false,
divideByCamelHumps = true,
)
17.Explain higher-order functions.
A higher-order function is a function that returns a function or accepts functions as parameters.
18.What is a lambda expression in Kotlin?
A lambda expression is a function that is passed immediately without being declared.
19.How do you use lambda expressions with higher-order functions?
You can use lambda expressions with high order functions by passing the lambda expressions directly to higher-order functions.
Example
val sum = { x: Int, y: Int -> x + y }
val result = performOperation(5, 6, sum)
Or
val resultDirect = performOperation(5, 6) { x, y -> x + y }
20.What distinguishes an anonymous function from a lambda expression?
- Lambdas are generally shorter and more concise.
- Lambdas use {} with -> for parameters and body, while anonymous functions use the fun keyword.
- Anonymous functions allow explicit return types, while lambdas infer the return type.
21.Explain the use of it in lambda expressions.
it is used to allow access to an object if the argument name is not specified.
Example
fun getRandomInt(): Int {
return Random.nextInt(100).also {
writeToLog("getRandomInt() generated value $it")
}
}
val i = getRandomInt()
println(i)
22.How do you define an extension function in Kotlin?
When defining an extension function, the type being extended is referenced by the receiver type that comes before the function name.
Example
fun MutableList<Int>.swap(index1: Int, index2: Int) {
val tmp = this[index1]
this[index1] = this[index2]
this[index2] = tmp
}
Collections
23.What are the different types of collections in Kotlin?
The following is a list of collection types:
- List
- Set
- Map or dictionary(This is a set of key-value pairs)
24.How do you create a list in Kotlin?
List offers indexed access to its elements and stores them in a predetermined order. Indices begin at zero, the first element's index, and proceed to lastIndex, or (list.size - 1)
Example
val numbers = listOf("one", "two", "three", "four")
println("Number of elements: ${numbers.size}")
25.What is the difference between List and MutableList?
The difference is that a MutableList has write operations, such as the ability to add or remove elements at particular positions.
Example
val numbers = mutableListOf(1, 2, 3, 4)
numbers.add(5)
numbers.removeAt(1)
numbers[0] = 0
numbers.shuffle()
println(numbers)
[4, 5, 0, 3]
26.How do you create a set in Kotlin?
A Set<T> usually stores unique elements with unspecified order.
Example
val numbers = setOf(1, 2, 3, 4)
println("Number of elements: ${numbers.size}")
27.What is the difference between Set and MutableSet?
The difference between Set and MutableSet is that a MutableSet has write operations.
28.How do you create a map in Kotlin?
A map can be created in two ways:
A map can be created in two ways:
- Using mapOf Function
The key-value pairs provided are used by the mapOf method to generate an immutable map.
Example
val map: Map<String, Int> = mapOf("one" to 1, "two" to 2, "three" to 3)
println(map) // Output: {one=1, two=2, three=3}
- Using Empty Map:
The emptyMap method can be used to build an empty immutable map.
Example
val emptyMap: Map<String, Int> = emptyMap()
println(emptyMap) // Output: {}
29.What is the difference between Map and MutableMap?
MutableMap allows you to freely add and remove pairs of objects, as contrast to Map, which is an immutable collection.
30.How do you filter a collection in Kotlin?
You can filter a collection by using the filter function (filter() ).
Filter() returns the collection elements that match a predicate when it is invoked with one. The resultant collection is a List for both List and Set, and a Map for Map.
Example
val numbers = listOf("one", "two", "three", "four")
val longerThan3 = numbers.filter { it.length > 3 }
println(longerThan3)
val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key11" to 11)
val filteredMap = numbersMap.filter { (key, value) -> key.endsWith("1") && value > 10}
println(filteredMap)
31.What is the map function, and how is it used?
Kotlin's map function is a transformation function that may be used to apply a specified function to each element in a collection, like a list or set, and then return a new list with the function's results.
32.How do you sort a collection in Kotlin?
In Kotlin, you can sort collections in various ways using the standard library functions.You can use sorted() and sortedDescending() functions to sort in a natural order in ascending and descending order or use sortedBy() and sortedByDescending() functions to sort using a specific criteria.
Example
val numbers = listOf("eight", "nine", "ten", "eleven")
val sortedNumbers = numbers.sortedBy { it.length }
println("Sorted by length ascending: $sortedNumbers")
val sortedByLast = numbers.sortedByDescending { it.last() }
println("Sorted by the last letter descending: $sortedByLast")
Control Flow
33.How are expressions applied in Kotlin?
Expressions are an essential component of Kotlin language and are employed in many different contexts, from straightforward computations to intricate logic. In contrast to statements, which carry out operations, expressions generate values.
34.Describe how the when expression is used.
When expression in kotlin defines a conditional expression with numerous branches.
Example
val x = 5
val result = when (x) {
1 -> "one"
2 -> "two"
3 -> "three"
else -> "unknown"
}
println(result) // Output: unknown
35.Highlight the use of while loops in Kotlin?
While loops in Kotlin execute their body continually as long as their condition is met.
Example
fun main() {
var counter = 5
do {
println("Counter: $counter")
counter--
} while (counter > 0)
}
36.What is the use of break and continue in loops?
The control flow statements break and continue are used in Kotlin to govern how loops are executed. By ending the loop early or moving on to the following iteration, they provide you control over the flow.
37.What is a range in Kotlin?
A range checks whether a number is within a range using in operator.
Example
val x = 7
val y = 8
if (x in 1..y+1) {
println("fits in range")
}
38.Explain how to iterate over a range in Kotlin?
You can use a for loop to iterate over range in Kotlin.
Example
for (x in 1..5) {
print(x)
}
39.What are labels and how are they used in Kotlin?
Labels are identifiers in Kotlin that are used to point to particular points in the code, mostly to manage the flow of lambdas and other constructs like lambdas. When working with lambda expressions or needing to exit or resume from nested loops, labels come in handy.
Example
loop@ for (i in 1..30) {
for (j in 1..30) {
if (...) break@loop
}
}
40.What are smart casts in Kotlin?
One of Kotlin's most useful features is smart casts, which, when the compiler determines that the cast is safe, automatically cast a variable to a particular type within a specified scope. The code becomes more understandable and simple as a result, eliminating the requirement for explicit casting.
Object-Oriented Programming(OOP)
41.How do you create a class in Kotlin?
In Kotlin, classes are declared with the class keyword.
Example
class Person { /*...*/ }
42.What are primary and secondary constructors?
In Kotlin the primary constructor is specified in the class header after the class name and optional type parameter.
Example
class Person constructor(firstName: String) { /*...*/ }
or
class Person(firstName: String) { /*...*/ }
Secondary constructors are optional and are prefixed by the constructor keyword. They serve as alternatives for initializing an object.
Example
class Car(val models: MutableList<Model> = mutableListOf())
class Model {
constructor(vehicle: Car) {
vehicle.models.add(this) // this model is added to the list of the vehicle models.
}
}
43.How do you inherit a class in Kotlin?
In Kotlin, you can use the : Superclass() syntax after the subclass name to inherit from it. To make a class inheritable, mark it with the open keyword.
Example
// Superclass (Parent class)
open class Animal(val name: String) {
open fun makeSound() {
println("Animal $name makes a sound")
}
}
// Subclass (Child class) inheriting from Animal
class Dog(name: String) : Animal(name) {
override fun makeSound() {
println("Dog $name barks")
}
}
fun main() {
val dog = Dog("Buddy")
dog.makeSound() // Output: Dog Buddy barks
}
44.Explain the use of open keyword in Kotlin.
In Kotlin the open keyword can be used to mark a class, function, or property as open for inheritance or overriding by subclasses.
45.What are abstract classes and methods?
Abstract classes are denoted by abstract keyword.They cannot be instantiated directly.
46.What is an interface, and how is it different from an abstract class?
An interface contains declarations of abstract methods and method implementations.However,they differ from an abstract class because they cannot store state.
47.How do you implement multiple interfaces in Kotlin?
A class in Kotlin can implement more than one interface, which enables it to inherit from other classes and give implementations for any method those classes provide.
Example
interface Interface1 {
fun method1()
}
interface Interface2 {
fun method2()
}
class MyClass : Interface1, Interface2 {
override fun method1() {
println("Implementation of method1")
}
override fun method2() {
println("Implementation of method2")
}
}
48.Explain the concept of delegation in Kotlin.
Delegation is a Kotlin design pattern in which one object assigns part of its duties to another. Classes can achieve behavior reuse without explicitly inheriting from another class thanks to this design, which prioritizes composition and code reuse over inheritance.Delegates are denoted using by keyword.
49.What are sealed classes?
A sealed class in Kotlin is used to symbolize hierarchies of restricted classes, in which a type can have a limited number of subclasses. This makes the class hierarchy exhaustive and predictable since it requires that all subclasses of a sealed class be specified in the same file as the sealed class.
50.How do you create an enum class in Kotlin?
An enum class is created using the enum keyword with enum constants separated by commas.
Example
enum class Car {
Toyota, Subaru,BMW
}
Interview Tip
By practising the interview questions and running the code in Kotlin playground,you will be able to grasp very many concepts within a very short time.This will give you the confidence to ace any interview and succeed.
share
Android Expert developing mobile applications with 4+ Years of Experience.