Cheat Sheet for Kotlin
I had prepared a list of most common questions asked during Kotlin Android Interviews for Android developer profile. Therefore, if you are preparing for Android Interviews, then this article is a must for you.
A visibility modifier or access specifier also called as access modifier is a concept that is used to define the scope of something in a programming language. In Kotlin, we have four visibility modifiers:
- private: visible inside that particular class or file containing the declaration.
- protected: visible inside that particular class or file and also in the subclass of that particular class where it is declared.
- internal: visible everywhere in that particular module.
- public: visible to everyone.
Question: What are the types of constructors in Kotlin?
Constructors in Kotlin are of two types:
- Primary — These are defined in the class headers. They cannot hold any logic. There’s only one primary constructor per class.
- Secondary — They’re defined in the class body. They must delegate to the primary constructor if it exists. They can hold logic. There can be more than one secondary constructors.
The init block gets called immediately after the primary constructor but before the secondary constructor. A class can have more than one init block, in this case, the initializer blocks are executed in the same order as they appear in the class body considering the properties if there are any in between.
Question: How to check the null status of latintent variable?
lateinit var file: File
if (::file.isInitialized) { ... }
Question: How can I share viewModel between activities?
viewModel cannot be directly shared between activities however, if you store viewmodelfactory in application class and retrieve factory object from activities and access viewmodel then you can share state of view model between activities.
Question: Data sharing between Fragments using viewModel
Using SharedViewModel, we can communicate between fragments. If we consider two fragments, both the fragments can access the ViewModel through their activity.
Here, one fragment updates the data within the ViewModel which is shared between both the fragments and another fragment observes the changes on that data.
val model = ViewModelProvider(requireActivity()).get(SharedViewModel::class.java)
Question: Explain about Scope functions:
Scope functions are those functions whose sole purpose is to execute a block of code within the context of an object. A temporary scope of an object is created where it can be accessed without its name.
Object reference by this - Run, Apply, With refer to the context object as a lambda receiver - by keyword this
. Hence, in their lambdas, the object is available as it would be in ordinary class functions.
Object reference by it - Let, Also have the context object as a lambda argument. If the argument name is not specified, the object is accessed by the implicit default name it
.
returns Context Object - Also, Apply
returns Lamba Result - Let, Run, With
Question: What is higher order function?
In Kotlin, a function can be passed as a parameter or can be returned from a function, the function which does the same is known as a higher-order function. In other words, a higher-order function is a function that takes functions as parameters or returns a function.
Question: Explain about Job and SupervisorJob?
A background job that can be arranged in a parent-child hierarchy. Cancellation of any parent will lead to the cancellation of all its children immediately, and failure or cancellation of any child jobs other than CancellationException lead to cancellation of its parent. Whereas a supervisor job is just a job, but its children can fail independently without taking down its parent.
Question: What is the difference between safe calls (?.) and null check(!!)?
Safe call operator i.e.? is used to check if the value of the variable is null or not. If it is null, then null will be returned otherwise it will return the desired value.
var language: String? = "Kotlin"
println(language?.length) // 6
language = null
println(language?.length) // null
If you want to throw NullPointerException when the value of the variable is null, then you can use the null check or !! operator.
var language: String? = "Kotlin"
println(language?.length) // 6
language = null
println(language!!.length) // Throws KotlinNullPointerException
Question: What is Elvis operator in Kotlin?
In Kotlin, you can assign null values to a variable by using the null safety property. To check if a value is having null value, then you can use if-else or can use the Elvis operator i.e. ?: For example:
var name:String? = "Kotlin"
val nameLength = name?.length ?: -1
println(nameLength)
The Elvis operator( ?: ) used above will return the length of name if the value is not null otherwise if the value is null, then it will return -1.
Question: What is the use of @JvmStatic, @JvmOverloads, and @JvmFiled in Kotlin?
@JvmStatic: This annotation is used to tell the compiler that the method is a static method and can be used in Java code.
@JvmOverloads: To use the default values passed as an argument in Kotlin code from the Java code, we need to use the @JvmOverloads annotation.
@JvmField: To access the fields of a Kotlin class from Java code without using any getters and setters, we need to use the @JvmField in the Kotlin code.
Question: Can we use primitive types such as int, double, float in Kotlin?
In Kotlin, we can't use primitive types directly. We can use classes like Int, Double, etc. as an object wrapper for primitives. But the compiled bytecode has these primitive types.
Question: What is String Interpolation in Kotlin?
If you want to use some variable or perform some operation inside a string, then String Interpolation can be used. You can use the $ sign to use some variable in the string or can perform some operation in between {} sign.
var language = "Kotlin"
print("I am new to $language")
Question: Is there any difference between == operator and === operator?
Yes. The == operator is used to compare the values stored in variables, and the === operator is used to check if the reference of the variables are equal or not. But in the case of primitive types, the === operator also checks for the value and not reference.
// primitive example
val int1 = 10
val int2 = 10
println(int1 == int2) // true
println(int1 === int2) // true
// wrapper example
val num1 = Integer(10)
val num2 = Integer(10)
println(num1 == num2) // true
println(num1 === num2) //false
Question: How to choose between a switch and when in Kotlin?
Whenever we want to handle many if-else conditions, then we generally use switch-case statements. But Kotlin provides a more concise option i.e. in Kotlin, we can use when in place of the switch. And, when can be used as:
# expression
# arbitrary condition expression
# without argument
# with two or more choices
when(number) {
1 -> println("One")
2, 3 -> println("Two or Three")
4 -> println("Four")
else -> println("Number is not between 1 and 4")
}
Question: What is the difference between FlatMap and Map in Kotlin?
FlatMap is used to combine all the items of lists into one list.
Map is used to transform a list based on certain conditions.
Question: What are extension functions in Kotlin?
Extension functions are like extensive properties attached to any class in Kotlin. By using extension functions, you can add some methods or functionalities to an existing class even without inheriting the class. For example: Let's say, we have views where we need to play with the visibility of the views. So, we can create an extension function for views like,
fun View.show() {
this.visibility = View.VISIBLE
}
fun View.hide() {
this.visibility = View.GONE
}
and to use it we use, like,
button.hide()
Question: What is an infix function in Kotlin?
An infix function is used to call the function without using any bracket or parenthesis just like English language. You need to use the infix keyword to use the infix function.
class Operations {
var x = 10;
infix fun minus(num: Int) {
this.x = this.x - num
}
}
fun main() {
val opr = Operations()
opr minus 8
print(opr.x)
}
One more important thing to notice in infix function is that these are those functions which accepts only one parameter. The examples of infix function in Koltin are 'downTo' and 'in' used in for loops.
Question: What is an inline function in Kotlin?
Inline function instruct compiler to insert complete body of the function wherever that function got used in the code. To use an Inline function, all you need to do is just add an inline keyword at the beginning of the function declaration.
Question: What are Reified types in Kotlin?
When you are using the concept of Generics to pass some class as a parameter to some function and you need to access the type of that class, then you need to use the reified keyword in Kotlin.
For example:
inline fun <reified T> genericsExample(value: T) {
println(value)
println("Type of T: ${T::class.java}")
}
fun main() {
genericsExample<String>("Learning Generics!")
genericsExample<Int>(100)
}
Question: What is the operator overloading in Kotlin?
This concept was not there in Java. In Kotlin, we can use the same operator to perform various tasks, and this is known as operator overloading.
To do so, we need to provide a member function or an extension function with a fixed name and operator keyword before the function name because normally also, when we are using some operator then under the hood some function gets called.
For example, if you are writing num1+num2, then it gets converted to num1.plus(num2), and if we are not writing operator in front of function then it will give compilation error.
fun main() {
val bluePen = Pen(inkColor = "Blue")
bluePen.showInkColor()
val blackPen = Pen(inkColor = "Black")
blackPen.showInkColor()
val blueBlackPen = bluePen + blackPen
blueBlackPen.showInkColor()
}
operator fun Pen.plus(otherPen: Pen):Pen{
val ink = "$inkColor, ${otherPen.inkColor}"
return Pen(inkColor = ink)
}
data class Pen(val inkColor:String){
fun showInkColor(){ println(inkColor)}
}
The main drawback of operator overloading is that in increases the complexity of the project.
Question: What are pair and triple in Kotlin?
Pair and Triples are used to return two and three values respectively from a function and the returned values can be of the same data type or different.
val pair = Pair("My Age: ", 25)
print(pair.first + pair.second)
Question: What are labels in Kotlin?
Any expression written in Kotlin is called a label. For example, if we are having a for-loop in our Kotlin code then we can name that for-loop expression as a label and will use the label name for the for-loop.
We can create a label by using an identifier followed by the @ sign. For example, name@, loop@, xyz@, etc. The following is an example of a label:
loop@ for (i in 1..10) {
println(" i $i")
}
The name of the above for-loop is loop.
Question: What are the benefits of using a Sealed Class over Enum?
Sealed classes give us the flexibility of having different types of subclasses and also containing the state. The important point to be noted here is the subclasses that are extending the Sealed classes should be either nested classes of the Sealed class or should be declared in the same file as that of the Sealed class.
If this has helped you or you believe this can help other developers in cracking Android Interviews, then please do share this with others as well.
Best of luck for interview!! May you come out with flying colors.
Comments
Post a Comment