Kotlin Interview Questions and Answers from FullStack.Cafe
Kotlin is immensely practical. It addresses the problems that developers have, and not some guys in the academia. So, it has type inference, it has amazing type safety, good collection library, and concurrency library to top it. And it's now official - a lot of organisations are migrating their backend applications to Kotlin, and this trend is not likely to end soon. Follow along to check the most complete and comprehensive collection of the most common and advanced Kotlin Interview Questions every Android developer should know in 2020.
You could also find all the answers here π https://www.fullstack.cafe/Kotlin.
Questions Details:
In Java an array can be initialized such as:
int numbers[] = new int[] {10, 20, 30, 40, 50}
How does Kotlin's array initialization look like?
Answer:
val numbers: IntArray = intArrayOf(10, 20, 30, 40, 50)
π Source: stackoverflow.com
Answer:
In Kotlin, you can concatenate
- using string interpolation / templates
val a = "Hello"
val b = "World"
val c = "$a $b"
- using the + /
plus()
operator
val a = "Hello"
val b = "World"
val c = a + b // same as calling operator function a.plus(b)
val c = a.plus(b)
print(c)
- using the
StringBuilder
val a = "Hello"
val b = "World"
val sb = StringBuilder()
sb.append(a).append(b)
val c = sb.toString()
print(c)
π Source: stackoverflow.com
Answer:
fold
takes an initial value, and the first invocation of the lambda you pass to it will receive that initial value and the first element of the collection as parameters.
listOf(1, 2, 3).fold(0) { sum, element -> sum + element }
The first call to the lambda will be with parameters 0
and 1
.
Having the ability to pass in an initial value is useful if you have to provide some sort of default value or parameter for your operation.
reduce
doesn't take an initial value, but instead starts with the first element of the collection as the accumulator (calledsum
in the following example)
listOf(1, 2, 3).reduce { sum, element -> sum + element }
The first call to the lambda here will be with parameters 1
and 2
.
π Source: stackoverflow.com
Questions Details:
How to remove duplicates from an Array<String?>
in Kotlin?
Answer:
Use the distinct
extension function:
val a = arrayOf("a", "a", "b", "c", "c")
val b = a.distinct() // ["a", "b", "c"]
You can also use:
toSet
,toMutableSet
toHashSet
- if you don't need the original ordering to be preserved
These functions produce a Set
instead of a List
and should be a little bit more efficient than distinct.
π Source: stackoverflow.com
Answer:
-
var is like
general
variable and it's known as a mutable variable in kotlin and can be assigned multiple times. -
val is like
Final
variable and it's known as immutable in Kotlin and can be initialized only single time.
+----------------+-----------------------------+---------------------------+
| | val | var |
+----------------+-----------------------------+---------------------------+
| Reference type | Immutable(once initialized | Mutable(can able to change|
| | can't be reassigned) | value) |
+----------------+-----------------------------+---------------------------+
| Example | val n = 20 | var n = 20 |
+----------------+-----------------------------+---------------------------+
| In Java | final int n = 20; | int n = 20; |
+----------------+-----------------------------+---------------------------+
π Source: stackoverflow.com
Answer:
Use var where value is changing frequently. For example while getting location of android device:
var integerVariable : Int? = null
Use val where there is no change in value in whole class. For example you want set textview or button's text programmatically.
val stringVariables : String = "Button's Constant or final Text"
π Source: stackoverflow.com
Answer:
We frequently create classes whose main purpose is to hold data. In Kotlin, this is called a data class and is marked as data
:
data class User(val name: String, val age: Int)
To ensure consistency and meaningful behavior of the generated code, data classes have to fulfill the following requirements:
- The primary constructor needs to have at least one parameter;
- All primary constructor parameters need to be marked as val or var;
- Data classes cannot be abstract, open, sealed or inner;
π Source: kotlinlang.org
Answer:
The primary constructor is part of the class header. Unlike Java, you don't need to declare a constructor in the body of the class. Here's an example:
class Person(val firstName: String, var age: Int) {
// class body
}
The main idea is by removing the constructor keyword, our code gets simplified and easy to understand.
π Source: www.programiz.com
Answer:
Just use object
.
object SomeSingleton
The above Kotlin object will be compiled to the following equivalent Java code:
public final class SomeSingleton {
public static final SomeSingleton INSTANCE;
private SomeSingleton() {
INSTANCE = (SomeSingleton)this;
System.out.println("init complete");
}
static {
new SomeSingleton();
}
}
This is the preferred way to implement singletons on a JVM because it enables thread-safe lazy initialization without having to rely on a locking algorithm like the complex double-checked locking.
π Source: medium.com
Questions Details:
What will be the output?
val aVar by lazy {
println("I am computing this value")
"Hola"
}
fun main(args: Array<String>) {
println(aVar)
println(aVar)
}
See π Answer
See π Answer
See π Answer
Questions Details:
Why is this code wrong?
class Student (var name: String) {
init() {
println("Student has got a name as $name")
}
constructor(sectionName: String, var id: Int) this(sectionName) {
}
}
See π Answer
See π Answer
See π Answer
See π Answer
See π Answer
See π Answer
See π Answer
See π Answer
See π Answer
See π Answer
See π Answer
See π Answer
See π Answer
See π Answer
See π Answer
See π Answer
See π Answer
See π Answer
Q31: What is the idiomatic way to deal with nullable values, referencing or converting them? βββ
Questions Details:
If I have a nullable type Xyz?
, I want to reference it or convert it to a non-nullable type Xyz
. What is the idiomatic way of doing so in Kotlin?
See π Answer
See π Answer
Questions Details:
Can you rewrite this Java code in Kotlin?
public class Singleton {
private static Singleton instance = null;
private Singleton(){
}
private synchronized static void createInstance() {
if (instance == null) {
instance = new Singleton();
}
}
public static Singleton getInstance() {
if (instance == null) createInstance();
return instance;
}
See π Answer
See π Answer
See π Answer
See π Answer
See π Answer
See π Answer
Q39: What is the purpose of Unit-returning in functions? Why is VALUE there? What is this VALUE? βββ
Questions Details:
Explain what is the purpose of Unit-returning in functions? Why is VALUE there? What is this VALUE?
fun printHello(name : String?) : Unit {
if (name != null)
print("Hello, $name!")
else
print("Hi there!")
// We don't need to write 'return Unit.VALUE' or 'return', although we could
}
See π Answer
See π Answer
See π Answer
Questions Details:
Consider:
class Message(message: String, signature: String) {
val body = MessageBody()
init {
body.text = message + "\n" + signature
}
}
Do you see any refactoring that could be done?
See π Answer
See π Answer
See π Answer
See π Answer
See π Answer
See π Answer
Questions Details:
Given the following Kotlin class:
data class Test(val value: Int)
How would I override the Int getter so that it returns 0
if the value negative?
See π Answer
See π Answer
Questions Details:
Assume that KeyAdapter
is an abstract class with several methods that can be overridden.
In java I can do:
KeyListener keyListener = new KeyAdapter() {
@Override public void keyPressed(KeyEvent keyEvent) {
// ...
}
};
How to do the same in Kotlin?
See π Answer
See π Answer
See π Answer
See π Answer
Questions Details:
Consider:
val generator = PasswordGenerator()
generator.seed = "someString"
generator.hash = {s -> someHash(s)}
generator.hashRepititions = 1000
val password: Password = generator.generate()
How would you refactor this code using run
extension function?
See π Answer
See π Answer
Questions Details:
Let's say I want to override the Int getter so that it returns 0 if the value negative for the data class. What's bad with that approach?
data class Test(private val _value: Int) {
val value: Int
get() = if (_value < 0) 0 else _value
}
See π Answer
See π Answer
See π Answer
Q59: Why do we use βcompanion objectβ as a kind of replacement for Java static fields in Kotlin? βββββ
See π Answer
Q60: Imagine you moving your code from Java to Kotlin. How would you rewrite this code in Kotlin? βββββ
Questions Details:
public class Foo {
private static final Logger LOG = LoggerFactory.getLogger(Foo.class);
}
See π Answer
See π Answer
Q62: What is the difference between launch/join and async/await in Kotlin coroutines? βββββ
See π Answer
Q63: What is a motivation to make classes final by default in Kotlin? Do you agree with that decision? βββββ
See π Answer
See π Answer
See π Answer
See π Answer
See π Answer
See π Answer