Codersee
Kotlin on the backend
Codersee
Kotlin on the backend
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.
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.
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.
Kotlin mainly targets the JVM, Android, JavaScript, and Native.
We can use it for various types of development, such as for example, server-side development, Android, web development or desktop development.
Kotlin combines both functional and object-oriented constructs.
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).
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.
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
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.
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
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.
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") }
By using an infix operator as
.
val newReferenceObject = oldReferenceObject as NewType
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
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.
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 """
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("#")
A Unit is a type and void is only a way to inform the compiler, that the method does not return any value.
Many of them.
Public.
It is used for a top-level element to be visible within the same module.
No, they are not.
Kotlin does not have bitwise operators. For bitwise operations Kotlin has special infix functions:
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()
.
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.
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.
To keep it visible only within the same file- that’s what private modifier allows for top-level declarations.
class SomeClass(val one: String, two: String) {}
One is a property and two is just a parameter of the primary constructor.
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
Varargs are parameters allowing a variable number of arguments to be passed to the function.
Only one parameter can be marked as vararg.
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.
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
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.
No.
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.
No.
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().
No, each time we invoke an anonymous object we get a new instance.
x in range //Check if the value is in a range existingRange.reversed() //Reverse a range
Yes, we can.
val a = if (someCondition) { 12 }
Compilation error. If-else statement used as an expression must have both if and else statement.
Both try and catch blocks can return a value. Finally can not.
When it is the last argument during function invocation.
Yes, in Kotlin it is possible.
Yes, it can.
For example, we can use getOrElse()
or getOrNull()
functions.
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.
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.
thanks bro