Top 50 Kotlin Interview Questions and Answers [2023]

1. What is Kotlin and why was it developed?

Answer: Kotlin is a statically-typed, cross-platform, general-purpose programming language. It was developed by JetBrains as an alternative to Java, offering improved performance, better readability, and more expressive syntax.

2. What are the key features of Kotlin?

Answer: Some of the key features of Kotlin include null safety, type inference, extension functions, properties, data classes, and more. Kotlin also supports functional programming, coroutines, and interop with Java code.

3. Can you explain the difference between Kotlin and Java?

Answer: Kotlin offers several advantages over Java, including null safety, improved readability and conciseness of code, and support for functional programming. Kotlin also has better type inference and handling of null values.

4. What are the advantages of using Kotlin over Java?

Answer: Some of the advantages of using Kotlin over Java include improved performance, reduced boilerplate code, null safety, and improved type inference. Kotlin also offers better support for functional programming and coroutines.

5. What are the basic syntaxes of Kotlin?

Answer: Some of the basic syntaxes of Kotlin include variable declaration, function definition, control structures, class definition, and more. For example:

// variable declaration
var name: String = "John Doe"

// function definition
fun printHello() {
println("Hello")
}

// class definition
class Person(val name: String, val age: Int)

6. Can you explain the concept of null safety in Kotlin?

Answer: Null safety is a feature in Kotlin that helps prevent null pointer exceptions. In Kotlin, variables cannot be assigned a null value by default. If a variable can be null, it must be explicitly marked as nullable. For example:

var name: String = "John Doe"
var age: Int? = null // nullable type

7. How does Kotlin handle extension functions?

Answer: Extension functions in Kotlin allow you to add new functionality to existing classes without having to inherit from them or use any type of design pattern. You can add an extension function to a class by using the fun keyword followed by the class name and the function name. For example:

fun String.greet() {
println("Hello, $this")
}

"John Doe".greet() // Output: Hello, John Doe

8. Can you explain the concept of properties in Kotlin?

Answer: Properties in Kotlin are a concise way to declare a getter and setter for a field. You can declare a property using the val or var keyword followed by the property name, type, and an optional initial value. For example:

class Person {
val name: String = "John Doe"
var age: Int = 30
}

9.How does Kotlin handle data classes?

Answer: Data classes in Kotlin are used to represent simple data objects. You can create a data class by using the data keyword followed by the class definition. Data classes automatically generate functions such as equals, hashCode, toString, and more. For example:

data class Person(val name: String, val age: Int)

10. What are higher-order functions in Kotlin and how are they used?

Answer: Higher-order functions in Kotlin are functions that either accept functions as parameters or return functions as values. Higher-order functions can be used to write more concise, readable, and reusable code. For example:

fun processNumbers(list: List<Int>, operation: (Int) -> Int): List<Int> {
return list.map(operation)
}

fun square(x: Int) = x * x

val numbers = listOf(1, 2, 3, 4, 5)
val squares = processNumbers(numbers, ::square)

11. Can you explain the concept of lambdas in Kotlin?

Answer: Lambdas in Kotlin are anonymous functions that can be passed as arguments to higher-order functions. They are defined using the -> operator and can be assigned to variables or passed as arguments to functions. For example:

val square = { x: Int -> x * x }
val numbers = listOf(1, 2, 3, 4, 5)
val squares = numbers.map(square)

12. What are coroutines in Kotlin and how are they used?

Answer: Coroutines in Kotlin are a way to write asynchronous, non-blocking code. They are lightweight and can be used to write code that runs concurrently. Coroutines can be used for tasks such as network I/O, database operations, and more. For example:

suspend fun fetchData(): String {
// Perform some long running operation
return "Data fetched"
}

GlobalScope.launch {
val data = fetchData()
println(data)
}

13. What are sealed classes in Kotlin and how are they used?

Answer: Sealed classes in Kotlin are used to represent a closed set of types. A sealed class can only be extended within the same file. Sealed classes are useful when you want to limit the number of subclasses that can be created for a given class. For example:

sealed class Shape
data class Circle(val radius: Double) : Shape()
data class Rectangle(val width: Double, val height: Double) : Shape()
data class Triangle(val base: Double, val height: Double) : Shape()

14. What is the use of the when expression in Kotlin?

Answer: The when expression in Kotlin is used as a replacement for switch statements in other programming languages. The when expression takes an expression as input and evaluates a series of branches based on its value. For example:

fun evaluate(value: Int) {
when (value) {
1 -> println("One")
2 -> println("Two")
else -> println("Unknown")
}
}

15. What is the use of the try-catch block in Kotlin?

Answer: The try-catch block in Kotlin is used to handle exceptions that may be thrown during the execution of a program. The try block contains the code that may throw an exception, and the catch block contains the code that will handle the exception. For example:

fun divide(a: Int, b: Int) {
try {
val result = a / b
println(result)

16. Can you explain the concept of null safety in Kotlin?

Answer: Null safety in Kotlin is a feature that helps prevent NullPointerExceptions. In Kotlin, variables can be either null or non-null, and the type system helps enforce these constraints at compile time. For example:

var name: String = "John"
name = null // Compile error: Null can not be a value of a non-null type String

var lastName: String? = "Doe"
lastName = null // Valid

17. What is the use of the ?. operator in Kotlin?

Answer: The ?. operator in Kotlin is used to safely access properties or call methods on nullable objects. If the object is null, the expression returns null instead of throwing a NullPointerException. For example:

val name: String? = "John"
println(name?.length) // Output: 4

val lastName: String? = null
println(lastName?.length) // Output: null

18. What is the use of the !! operator in Kotlin?

Answer: The !! operator in Kotlin is used to explicitly tell the compiler that a variable is not null, and to suppress the null safety check. The !! operator should be used with caution, as it may result in a NullPointerException if the variable is actually null. For example:

val name: String? = "John"
println(name!!.length) // Output: 4

val lastName: String? = null

println(lastName!!.length) // Throws NullPointerException

19. Can you explain the difference between var and val in Kotlin?

Answer: var and val in Kotlin are used to declare variables. var is used to declare a mutable variable, which means that its value can be changed after it is declared. val is used to declare an immutable variable, which means that its value cannot be changed after it is declared. For example:

var name: String = "John"
name = "Jane" // Valid

val lastName: String = "Doe"
lastName = "Smith" // Compile error: Val cannot be reassigned

20. Can you explain the difference between a class and an object in Kotlin?

Answer: In Kotlin, a class is a blueprint for creating objects, while an object is a single instance of a class. A class can have multiple objects, while an object cannot have multiple classes. Objects can be used to create singleton classes or to group related functions together without creating a class. For example:

class Person {
var name: String = ""
var age: Int = 0
}

val person = Person()
person.name = "John"
person.age = 30

object Logger {
fun log(message: String) {
println(message)
}
}

Logger.log("Message")

21. Can you explain the difference between a constructor and a secondary constructor in Kotlin?

Answer: In Kotlin, a constructor is a special block of code that is executed when a new object of a class is created. There can be one primary constructor and multiple secondary constructors in a class. The primary constructor is defined directly in the class header and can contain properties and initializer blocks. Secondary constructors, on the other hand, are defined using the constructor keyword and must call the primary constructor or another secondary constructor. For example:

class Person constructor(var name: String) {
var age: Int = 0

constructor(name: String, age: Int) : this(name) {
this.age = age
}
}

val person1 = Person("John")
val person2 = Person("Jane", 32)

22. Can you explain the difference between open, final, and abstract in Kotlin?

Answer: open, final, and abstract in Kotlin are keywords used to control inheritance and polymorphism.

open class Shape {
open fun draw() {
println("Drawing a Shape")
}
}

class Circle : Shape() {
override fun draw() {
println("Drawing a Circle")
}
}

final class Square : Shape() {
override fun draw() {
println("Drawing a Square")
}
}

abstract class Triangle : Shape() {
abstract override fun draw()
}

23. Can you explain the difference between a sealed class and an enum class in Kotlin?

Answer: In Kotlin, a sealed class is a special type of class that can be extended only within the same file. Sealed classes are useful for representing a limited number of known subclasses, and are commonly used for defining an algebraic data type. An enum class, on the other hand, is a type that represents a fixed set of values, such as the days of the week.

For example:

sealed class Shape {
class Circle : Shape()
class Square : Shape()
class Triangle : Shape()
}

enum class Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

24. What is the difference between a lambda expression and an anonymous function in Kotlin?

Answer: In Kotlin, both lambda expressions and anonymous functions are used to declare inline functions. A lambda expression is a concise way of declaring a function literal, and consists of the function parameters, an arrow (->), and the function body. Anonymous functions, on the other hand, are declared using the fun keyword and can have a name, although it is not mandatory.

val sum = lambda: (Int, Int) -> Int = { x, y -> x + y }
val square = fun(x: Int): Int = x * x

25. Can you explain the difference between a variable and a constant in Kotlin?

Answer: In Kotlin, a variable is a reference to an object that can change its value over time, while a constant is an object that has a fixed value. Variables are declared using the var keyword, while constants are declared using the val keyword.

var x = 10
x = 20

val y = 10
y = 20 // Error: Val cannot be reassigned

26. Can you explain the difference between a nullable type and a non-null type in Kotlin?

Answer: In Kotlin, a nullable type is a type that can either contain a value or the special value null, while a non-null type cannot contain the value null. Nullable types are declared using a ? after the type, while non-null types are declared without the ?.

For example:

var name: String? = "John"
name = null

var age: Int = 30
age = null // Error: Type mismatch

27. Can you explain the difference between the !! and ?. operators in Kotlin?

Answer: The !! and ?. operators in Kotlin are used to handle null safety. The !! operator is used to force a nullable type to return its value, even if it is null, while the ?. operator is used to safely access properties and call methods on an object that may be null.

For example:

var name: String? = "John"

println(name!!.length) // Forces name to return its value, even if it is null

println(name?.length) // Safely accesses the length property of name, if it is not null

28. Can you explain the difference between a class and an object in Kotlin?

Answer: In Kotlin, a class is a blueprint that is used to define objects, while an object is an instance of a class. Classes are defined using the class keyword, and can have properties, methods, and constructors. Objects, on the other hand, are created using the object keyword, and are singleton instances of a class.

For example:

class Person {
var name: String = ""
var age: Int = 0
}

val person = Person()
person.name = "John"
person.age = 30

object Logger {
fun log(message: String) {
println(message)
}
}

Logger.log("Hello World")

29. Can you explain the difference between an interface and an abstract class in Kotlin?

Answer: In Kotlin, an interface is a blueprint for a class, similar to an abstract class, but with some key differences. Interfaces can contain method declarations, properties, and default implementations, but cannot contain constructors or instance variables. Abstract classes, on the other hand, can contain constructors, instance variables, and can provide a partial implementation for their subclasses.

For example:

interface Shape {
fun draw()
}

class Circle : Shape {
override fun draw() {
println("Drawing a Circle")
}
}
 
abstract class Rectangle {
abstract fun draw()
}
 
class Square : Rectangle() {
override fun draw() {
println("Drawing a Square")
}
}

30. How does Kotlin handle type inference?

Kotlin has a strong type inference system, which means that the compiler can infer the type of a variable or expression based on the context. This allows you to write less verbose code and reduces the need to explicitly specify the type of a variable.

Example:

val x = 5 // inferred as Int
val y = "Hello" // inferred as String
val z = x + y // inferred as String

31. Can you explain the difference between a sealed class and a regular class in Kotlin?

Answer: In Kotlin, a sealed class is a special kind of class that is used to restrict the number of subclasses that can be created. Sealed classes are defined using the sealed keyword, and can have a limited number of subclasses that are specified in the same file. Regular classes, on the other hand, can have any number of subclasses and can be created in different files.

sealed class Shape {
class Circle(var radius: Double) : Shape()
class Square(var side: Double) : Shape()
class Triangle(var base: Double, var height: Double) : Shape()
}

fun calculateArea(shape: Shape) = when (shape) {
is Shape.Circle -> Math.PI * shape.radius * shape.radius
is Shape.Square -> shape.side * shape.side
is Shape.Triangle -> 0.5 * shape.base * shape.height
}

val circle = Shape.Circle(10.0)
val square = Shape.Square(10.0)
val triangle = Shape.Triangle(10.0, 20.0)

println(calculateArea(circle))
println(calculateArea(square))
println(calculateArea(triangle))

32. Can you explain the difference between a companion object and an object in Kotlin?

Answer: In Kotlin, a companion object is a special kind of object that is associated with a class, while an object is a standalone instance of a class. Companion objects are used to define static-like properties and methods for a class, and can access the private properties and methods of the class. Objects, on the other hand, are used to create singleton instances of a class.

For example:

class Person {
var name: String = ""
var age: Int = 0

companion object {
fun createPerson(name: String, age: Int) = Person().apply {
this.name = name
this.age = age
}
}
}

val person = Person.createPerson("John", 30)

object Logger {
fun log(message: String) {
println(message)
}
}

Logger.log("Hello World")

33. Can you explain the difference between a data class and a regular class in Kotlin?

Answer: In Kotlin, a data class is a special kind of class that is used to represent data, while a regular class is a general-purpose class that can be used for any type of implementation. Data classes are defined using the data keyword, and automatically generate methods such as equals, hashCode, and toString based on their properties. Regular classes, on the other hand, require manual implementation of these methods.

For example:

data class Person(var name: String, var age: Int)

val person = Person("John", 30)
val person2 = Person("John", 30)

println(person == person2) // true
println(person.hashCode() == person2.hashCode()) // true
println(person.toString() == person2.toString()) // true

34. Can you explain the difference between an extension function and a regular function in Kotlin?

Answer: In Kotlin, an extension function is a special kind of function that extends the functionality of an existing class without modifying its source code. Extension functions are defined using the fun keyword followed by the name of the class that is being extended and a dot (.) before the function name. Regular functions, on the other hand, are independent functions that are not associated with any specific class.

For example:

fun String.toTitleCase() = this.split(" ").map { it.capitalize() }.joinToString(" ")

val title = "kotlin programming language".toTitleCase()
println(title) // Kotlin Programming Language

35. Can you explain the difference between a property accessor and a regular property in Kotlin?

Answer: In Kotlin, a property accessor is a special kind of property that provides a getter and setter for accessing its value, while a regular property is a simple property that has a single value. Property accessors are defined using the get and set keywords, and can be used to perform additional operations when accessing or setting the value of a property. Regular properties, on the other hand, can be accessed and modified directly.

For example:

class Person {
var name: String = ""
get() = field.capitalize()
set(value) {
field = value.trim()
}
}

val person = Person()
person.name = " john "
println(person.name) // John

36. Can you explain the difference between a lateinit property and a regular property in Kotlin?

Answer: In Kotlin, a lateinit property is a special kind of property that is used to initialize a non-null property after the instance of a class has been created, while a regular property must be initialized at the time of creation of the instance of the class. Lateinit properties are defined using the lateinit keyword, and must be non-nullable and can only be used for mutable properties. Regular properties can be nullable or non-nullable and can be used for both mutable and immutable properties.

For example:

class Person {
lateinit var name: String
var age: Int = 0
}

val person = Person()
person.name = "John"
person.age = 30
println("Name: ${person.name}, Age: ${person.age}") // Name: John, Age: 30

37. Can you explain the difference between a suspend function and a regular function in Kotlin?

Answer: In Kotlin, a suspend function is a special kind of function that can be paused and resumed later, while a regular function executes to completion. Suspend functions are defined using the suspend keyword and are used in conjunction with coroutines to perform long-running or blocking operations. Regular functions, on the other hand, are used for normal, non-blocking operations.

For example:

suspend fun fetchData(): String {
// perform long-running or blocking operation
return "Data fetched"
}

fun main() {
runBlocking {
val data = fetchData()
println(data) // Data fetched
}
}

38. Can you explain the difference between a constructor and an init block in Kotlin?

Answer: In Kotlin, a constructor is a special kind of function that is used to initialize an instance of a class, while an init block is a block of code that is executed when an instance of a class is created. A class can have one or multiple constructors, each with its own parameters and initializations, and the constructor that is called depends on the arguments passed when creating an instance of the class. An init block, on the other hand, is a simple block of code that is executed as part of the class initialization process, regardless of the constructor that is called.

For example:

class Person(val name: String) {
init {
println("Init block: $name")
}
}

class Student(name: String, val rollNo: Int) : Person(name) {
init {
println("Init block: $name, $rollNo")
}
}

val student = Student("John", 1)
// Init block: John
// Init block: John, 1

39. Can you explain the difference between a sealed class and a regular class in Kotlin?

Answer: In Kotlin, a sealed class is a special kind of class that can only be extended by its nested classes, while a regular class can be extended by any class. Sealed classes are defined using the sealed keyword, and are used to create restricted class hierarchies. Regular classes, on the other hand, can be extended by any class, anywhere in the codebase.

For example:

sealed class Shape {
class Circle(val radius: Double) : Shape()
class Square(val side: Double) : Shape()
class Triangle(val base: Double, val height: Double) : Shape()
}

fun calculateArea(shape: Shape) = when (shape) {
is Shape.Circle -> Math.PI * shape.radius * shape.radius
is Shape.Square -> shape.side * shape.side
is Shape.Triangle -> 0.5 * shape.base * shape.height
}

val circle = Shape.Circle(5.0)
println("Circle area: ${calculateArea(circle)}") // Circle area: 78.53981633974483

val square = Shape.Square(5.0)
println("Square area: ${calculateArea(square)}") // Square area: 25.0

val triangle = Shape.Triangle(5.0, 10.0)
println("Triangle area: ${calculateArea(triangle)}") // Triangle area: 25.0

40. Can you explain the difference between a class and an object in Kotlin?

Answer: In Kotlin, a class is a blueprint for creating objects, while an object is an instance of a class. A class can have properties, methods, and constructors, and can be extended and subclassed. An object, on the other hand, is a single instance of a class and can be used to access the properties and methods of the class. In Kotlin, an object can be created using the object keyword, and can be used as a singleton or a companion object.

class User {
val name: String
constructor(name: String) {
this.name = name
}
}

object UserService {
fun findUser(name: String) = User(name)
}

val user = UserService.findUser("John")
println(user.name) // John

41. Can you explain the difference between a var and a val in Kotlin?

Answer: In Kotlin, var is used to declare a variable that is mutable, meaning its value can be changed after it is initialized, while val is used to declare a variable that is immutable, meaning its value cannot be changed after it is initialized. var variables are declared using the var keyword, followed by the variable name, type and value. val variables are declared using the val keyword, followed by the variable name, type, and value.

For example:

var x = 5
x = 10
println(x) // 10

val y = 5
// y = 10 // Compile error: Val cannot be reassigned
println(y) // 5

42. Can you explain the difference between an open class and a final class in Kotlin?

Answer: In Kotlin, an open class is a class that can be extended or subclassed, while a final class is a class that cannot be extended or subclassed. Open classes are defined using the open keyword, and are used to create class hierarchies that can be extended by other classes. Final classes, on the other hand, are defined using the final keyword, and are used to create classes that cannot be subclassed or extended.

For example:

open class Shape {
open fun area() = 0.0
}

class Circle(val radius: Double) : Shape() {
override fun area() = Math.PI * radius * radius
}

val circle = Circle(5.0)
println("Circle area: ${circle.area()}") // Circle area: 78.53981633974483

43. Can you explain the difference between an interface and an abstract class in Kotlin?

Answer: In Kotlin, an interface is a collection of abstract methods and properties that a class can implement, while an abstract class is a class that cannot be instantiated but can be subclassed. An interface defines the structure of a class without providing its implementation, while an abstract class provides both a structure and an implementation. Interfaces are defined using the interface keyword, while abstract classes are defined using the abstract keyword.

interface Shape {
fun area(): Double
}

abstract class AbstractShape : Shape {
abstract override fun area(): Double
}

class Circle(val radius: Double) : Shape {
override fun area() = Math.PI * radius * radius
}

val circle = Circle(5.0)
println("Circle area: ${circle.area()}") // Circle area: 78.53981633974483

44. Can you explain the difference between a constructor and an init block in Kotlin?

Answer: A constructor is a special kind of function that is used to initialize an instance of a class, while an init block is a block of code that is executed when an instance of a class is created. A class can have one or multiple constructors, each with its own parameters and initializations, and the constructor that is called depends on the arguments passed when creating an instance of the class. An init block, on the other hand, is a simple block of code that is executed as part of the class initialization process, regardless of the constructor that is called.

For example:

class Person(val name: String) {
init {
println("Person created: $name")
}
}

class Employee(name: String, val employeeId: Int) : Person(name) {
init {
println("Employee created: $name, $employeeId")
}
}

val employee = Employee("John Doe", 123)
// Person created: John Doe
// Employee created: John Doe, 123

45. Can you explain the difference between a companion object and an object in Kotlin?

Answer: A companion object is an object that is associated with a class, while an object is a singleton object in Kotlin. A companion object is declared using the companion object keyword, and can be used to hold properties and functions that are associated with the class. An object declaration, on the other hand, creates a singleton object, which can be used to define utility functions, constants, or singleton instances of a class.

For example:

class Utils {
companion object {
fun formatString(str: String) = "Formatted: $str"
}
}

println(Utils.formatString("Hello World")) // Formatted: Hello World

object Logger {
fun log(message: String) = println(message)
}

Logger.log("Hello World") // Hello World

46. Can you explain the difference between a lazy property and an early-initialized property in Kotlin?

Answer: A lazy property is a property that is initialized the first time it is accessed, while an early-initialized property is a property that is initialized as soon as it is declared. A lazy property is declared using the lazy function, and can be used to defer the initialization of an object until it is actually needed. An early-initialized property, on the other hand, is initialized as soon as it is declared, and is stored in memory for the lifetime of the object.

For example:

class Person {
val name: String by lazy {
println("Initializing name...")
"John Doe"
}
}

val person = Person()
println(person.name) // Initializing name...
// John Doe

class Employee {
val name: String = run {
println("Initializing name...")
"John Doe"
}
}

val employee = Employee()
println(employee.name) // Initializing name...
// John Doe

47. Can you explain the difference between a try-catch block and a try-catch-finally block in Kotlin?

Answer: A try-catch block is used to handle exceptions that are thrown within a block of code, while a try-catch-finally block is used to handle exceptions and ensure that a block of code is executed, regardless of whether an exception is thrown or not. A try-catch block is declared using the try keyword, followed by a block of code that may throw an exception, followed by one or multiple catch blocks that handle exceptions of specific types. A try-catch-finally block is similar, but also includes a finally block that is executed after the try and catch blocks, regardless of whether an exception was thrown or not.

For example:

fun divide(num1: Int, num2: Int): Int {
try {
return num1 / num2
} catch (e: ArithmeticException) {
println("Exception caught: ${e.message}")
return 0
}
}

println(divide(10, 2)) // 5
println(divide(10, 0)) // Exception caught: / by zero

fun divideWithFinally(num1: Int, num2: Int): Int {
try {
return num1 / num2
} catch (e: ArithmeticException) {
println("Exception caught: ${e.message}")
return 0
} finally {
println("Finally block executed")
}
}

println(divideWithFinally(10, 2)) // 5
// Finally block executed
println(divideWithFinally(10, 0)) // Exception caught: / by zero
// Finally block executed

48. Can you explain the difference between a vararg and a spread operator in Kotlin?

Answer: A vararg is a special type of parameter that can accept a variable number of arguments, while a spread operator is used to pass an array of values as separate arguments to a function. A vararg parameter is declared using the vararg keyword, followed by the type of the argument, and can be accessed within the function as an array. The spread operator is represented by the * symbol, and is used to pass an array of values as separate arguments to a function.

For example:

fun printNumbers(vararg numbers: Int) {
for (number in numbers) {
println(number)
}
}

printNumbers(1, 2, 3, 4, 5)
// 1
// 2
// 3
// 4
// 5

fun sum(num1: Int, num2: Int, num3: Int) = num1 + num2 + num3

val numbers = intArrayOf(1, 2, 3)
println(sum(*numbers)) // 6

49. Can you explain the difference between an if-expression and an if-statement in Kotlin?

Answer: An if-expression is a shorthand way to return a value based on a condition, while an if-statement is used to execute a block of code based on a condition. An if-expression is declared using the if keyword, followed by a condition, and then a value that is returned if the condition is true, or an optional else branch that returns a value if the condition is false. An if-statement is declared using the if keyword, followed by a condition, and then a block of code that is executed if the condition is true, or an optional else branch that is executed if the condition is false.

For example:

fun getAbsoluteValue(num: Int) = if (num >= 0) num else -num

println(getAbsoluteValue(10)) // 10
println(getAbsoluteValue(-10)) // 10

fun printAbsoluteValue(num: Int) {
if (num >= 0) {
println(num)
} else {
println(-num
)
}
}
 
printAbsoluteValue(10) // 10
printAbsoluteValue(-10) // 10

50. Can you explain the difference between a `when expression` and a `switch statement` in Kotlin?

Answer: A `when expression` in Kotlin is a shorthand for a series of `if-else` statements and is similar to a `switch statement` in other programming languages. A `when expression` is declared using the `when` keyword, followed by a value to be matched, and then a series of branches that match the value with different patterns. If a match is found, the corresponding branch is executed and the value is returned. If no match is found, an optional `else` branch is executed.

A `switch statement` in other programming languages is typically used to match a single value against multiple cases and execute the corresponding code for the first match found. The `when expression` in Kotlin is more powerful, as it can match against multiple values, ranges, types, and even arbitrary expressions.

For example:

fun getDayOfWeek(day: Int) = when (day) {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
6 -> "Saturday"
7 -> "Sunday"
else -> "Invalid day"
}
 
println(getDayOfWeek(1)) // Monday
println(getDayOfWeek(7)) // Sunday
println(getDayOfWeek(0)) // Invalid day
chevron_right