Codersee

50 Kotlin interview questions

A featured image for category: Kotlin

1. Introduction

This article on Kotlin interview questions has been created to help you understand the basic concepts of Kotlin programming language for interview purposes. Whether you are a beginner or a highly experienced developer, core Kotlin plays a very crucial role in any Kotlin-related interview.

Given below you’ll find 50 interview questions with detailed answers which will help you build a solid foundation before you head to the interview.

2. Kotlin interview questions

1. What is Kotlin?

Kotlin is a cross-platform, statically typed, general-purpose programming language with type inference developed by JetBrains. The project started in 2010 and the first official 1.0 release was in 2016.

2. What are the Kotlin target platforms?

Kotlin mainly targets the JVM, Android, JavaScript, and Native.

3. What can we use Kotlin to?

We can use it for various types of development, such as for example, server-side development, Android, web development or desktop development.

4. Is Kotlin a functional language or an object-oriented one?

Kotlin combines both functional and object-oriented constructs.

5. What can we compile Kotlin to?

When targeting the JVM, Kotlin compiles to java bytecode. When targetting Javascript, it transpiles to ES5.1. When targetting native, it will produce platform-specific code (via LLVM).

6. Does Kotlin fully interoperate with Java?

It is designed to interoperate fully with Java, and the JVM version of its standard library depends on the Java Class Library. We can easily call Java code from Kotlin and vice versa.

7. What are some of the best Kotlin features?
  • Null Safety
  • Concise code
  • Immutability
  • Extension Functions
  • Data classes
  • Smart Casts
8. What is Null Safety and Nullable Types in Kotlin?

Kotlin’s type system is aimed at eliminating the danger of null references from code, also known as The Billion Dollar Mistake. The type system distinguishes between references that can hold null and those that can not.

val a: String = null  //Non-null reference- compilation error
val b: String? = null //Nullable reference- OK
9. What is the difference between a val and a var declaration?

They are both used to declare variables. The difference is that var declares a mutable variable and that val declares a read-only (assign-once) variable.

10. What’s the difference between a val and a constant?

Val is a read-only variable, but is not a constant: it can be initialized with the value of a variable (so its value doesn’t need to be known at compile-time), and if it is declared inside a construct that is repeatedly invoked (such as a function), it can take on a different value on each invocation. Also, it can refer to an object which is mutable. If we have a value that is truly constant (and is a String or a primitive type that is known at compile-time), we can declare it as an actual constant. However, we can do it only inside an object declaration or at the top level of the file.

val a = 1  //Read-only variable 
const val b = 2  //Constant
11. Does Kotlin allow to use of primitive types?

Kotlin does not have primitive types that are not classes. Some of the types, like numbers, booleans or characters, can have a special internal representation and can be represented as primitive values at runtime- but to the user, they look like ordinary classes.

12. How can we check the type of an object?

We can check whether the object conforms to a given type by using is operator, or it’s negated form !is.

if (obj is Number) {   
  print("Is a number")
} 

if (obj !is Number) {   
  print("Is not a number")
}
13. How can we cast an object?

By using an infix operator as.

val newReferenceObject = oldReferenceObject as NewType
14. What is the difference between “safe” and “unsafe” cast operator?

When we use an unsafe cast operator “as” an exception will be thrown if the cast is not possible. To avoid it we can use a nullable cast operator “as?” which returns null on failure.

val b = a as String   //Throws TypeCastException if a is null 
val c = a as? String //Returns null instead
15. What is a smart cast?

When we perform an is or !is check on a variable, the compiler tracks this information and automatically casts the variable to the target type in the scope where the is or !is check is true.

if(obj is String) {
  println("Found a String of length ${obj.length}")  //Casted automatically
}

//It works also on the right-hand side of "&&" and "||"
if(obj !is String && obj.length > 0) {
    return
}

But smart casts can work only if the compiler can guarantee that the variable hasn’t changed after the check- it does not work for mutable properties of a class.

16. What are the two types of string literals in Kotlin and what’s the difference between them?

Escaped strings and raw strings. Escaped strings are delimited by a single quote " and may have escaped characters in them. Raw strings are delimited by a triple quote """ contain no escaping and can contain newlines and any other characters.

val a = "Hello"
val text = """
    Hello
    World
"""
17. How can we remove leading whitespace inside a raw string?

We can remove it with trimMargin() function. By default | is used as a margin prefix.

val text = """
   | Hello
   |World
""".trimMargin()

But we can also choose another character and pass it as a parameter.

val text = """
   #Hello
   #World
""".trimMargin("#")
18. What’s the difference between a void and a Unit?

A Unit is a type and void is only a way to inform the compiler, that the method does not return any value.

19. How many public classes can a Kotlin file contain?

Many of them.

20. What visibility modifiers are presented in Kotlin?
  • private
  • protected
  • internal
  • public
21. What is the default visibility used if there is no explicit modifier?

Public.

22. What is an internal modifier used for?

It is used for a top-level element to be visible within the same module.

23. Are private members of an inner class visible to the outer class?

No, they are not.

24. What are bitwise operators in Kotlin?

Kotlin does not have bitwise operators. For bitwise operations Kotlin has special infix functions:

  • shl(bitCount: Int)- signed shift left
  • shr(bitCount: Int)- signed shift right
  • ushr(bitCount: Int)- unsigned shift right
  • and(other: Int)- bitwise AND
  • or(other: Int)- bitwise OR
  • xor(other: Int)- bitwise XOR
  • inv()- bitwise inversion
25. Does this code will compile?
val myInt = 10
var myLong = 22L

myLong = myInt

No, it won’t. Kotlin does not cast Int to Long or Float to Double automatically, but all number classes have a method to convert. So we can fix this code with myInt.toLong().

26. Which line will be the KotlinNullPointerException thrown in the following code?
val one = null
val two = one!!
val three = two.toUpperCase()

Line 2 – it will be thrown in the line of assertion, not in the line of invoking a function.

27. What happens when we compare a null reference with another object?
val one = null
val two = 1
println(one == null)

The equality operator is a safe operator, it will not throw an exception, it will return false.

28. What is the purpose of annotating a class as private?

To keep it visible only within the same file- that’s what private modifier allows for top-level declarations.

29. What is the difference between one and two in the following example?
class SomeClass(val one: String, two: String) {}

One is a property and two is just a parameter of the primary constructor.

30. What are the named arguments used for?

Named arguments are used to specify the names of arguments passed to the function. This makes our calls more readable. We can reorder named arguments and mix them with a positioned argument as long as all the position-based arguments are placed before named ones.

fun someFunction(one: Int, two: String) {}

someFunction(1, "example")  //OK
someFunction(two = "example", one = 1)  //OK
someFunction(1, two = "example")  //OK 
someFunction(one = 1, "example")  //Error: mixing named and positioned arguments is not allowed here
31. What are Varargs in Kotlin?

Varargs are parameters allowing a variable number of arguments to be passed to the function.

32. How many varargs might be placed in a parameter list?

Only one parameter can be marked as vararg.

33. Does the vararg parameter have to be the last one in a parameter list?

It does not have to be the last parameter, but when it is, values for the following parameters have to be passed using named argument syntax, or, if the parameter has a function type, by passing a lambda outside parentheses.

34. What is a spread operator?

It is the operator that unpacks an array into the list of values. It is used to pass an array as the vararg parameter.

fun someFunction(vararg one: Int) {}

val arr = intArrayOf(1,2)

someFunction(arr)  //ERROR
someFunction(*arr) //OK
35. Does the following code compile?
fun someFunction(vararg one: Int) {}

val arr = intArrayOf(1,2)

someFunction(*a,*b)
someFunction(*a, 2, 3)

Yes, with spread operator we can combine multiple arrays into one parameter, or pass additional values.

36. Do we have to declare a class as open when it is already declared as abstract?

No.

37. What is the purpose of creating companion objects?

They are used to create fields or functions inside a class that can be invoked without an instance of a class, f.e: factory methods or concepts similar to static fields and functions.

38. Can data classes be extended?

No.

39. What does this code do?
SomeClass.Companion.someFunc()

It invokes a function from a companion object which does not have any name explicitly specified. We can do it also without using the “”Companion””- SomeClass.someFunc().

40. Is an anonymous object a singleton?

No, each time we invoke an anonymous object we get a new instance.

41. How can we create a range, exclusive range, backward range or step range?
  • 1..10
  • 1 until 10
  • 10.downTo(1)
  • 1..10 step 2
42. How can we check if a value is in a range or reverse it?
x in range //Check if the value is in a range
existingRange.reversed() //Reverse a range
43. Can we assign a result of the if-else statement to the variable?

Yes, we can.

44. What will be the output of the following code?
val a = if (someCondition) {
        12
    }

Compilation error. If-else statement used as an expression must have both if and else statement.

45. Can try, catch or finally block return a value?

Both try and catch blocks can return a value. Finally can not.

46. When can we move a lambda outside parentheses?

When it is the last argument during function invocation.

47. Can lambda expression access a non-final or not effectively-final variable?

Yes, in Kotlin it is possible.

48. Can a List contain nulls?

Yes, it can.

49. What can we do to avoid IndexOutOfBoundException when getting an element from a collection?

For example, we can use getOrElse() or getOrNull() functions.

50. What is the difference between the following lines:
listOf(firstList, secondList) 
firstList.zip(secondList)
firstList+secondList
firstList.union(secondList)

The first one creates a list consisting of two lists. Zip function creates a list of pairs- but if one of the lists contains n elements and the second contains n+1 elements, the result list will consist of only n pairs. The third one creates a list of elements from both lists. The union joins both of the lists without duplicates.

3. Conclusion

In this post, we’ve covered 50 Kotlin interview questions. I hope that this list would have given you a better insight into core concepts of the Kotlin programming language and that it will help you prepare for the interview.

Did you find this post helpful? Maybe you would like to share some other questions with us? If so, please let us know in the comments below, by our Facebook page or group, or by using our contact form.

Leave a Reply

Your email address will not be published.

Categories

Author

Hi there! 👋

Hi there! 👋

My name is Piotr and I've created Codersee to share my knowledge about Kotlin, Spring Framework, and other related topics through practical, step-by-step guides. Always eager to chat and exchange knowledge.

Join the FREE weekly newsletter and get two free eBooks:

Image shows the covers of free ebooks accessible for newsletter subscribers.

You may opt out any time. Terms of Use and Privacy Policy.

To make Codersee work, we log user data. By using our site, you agree to our Privacy Policy and Terms of Use.