important Kotlin interview questions and answers

How  to create Singleton classes?

To use the singleton pattern for our class we must use the keyword object


object MySingletonClass

An object cannot have a constructor set. We can use the init block inside it though

Kotlin have the static keyword? How to create static methods in Kotlin?

NO. Kotlin doesn’t have the static keyword.
To create static method in our class we use the companion object.
Following is the Java code:


class A {
public static int returnMe() { return 5; }
}

The equivalent Kotlin code would look like this:


class A {
companion object {
fun a() : Int = 5
}
}

To invoke this we simply do: A.a().

What are the features you think are there in Kotlin but not in Java ?

Kotlin has quite a number of features that Java doesn’t. To name some of them, they are

  • Extension Functions
  • Null Safety
  • Smart casts
  • Range expressions
  • Operator Overloading
  • Data classes
  • Companion Objects
  • Coroutines

What kinds of programming does Kotlin support ?

Kotlin supports two types of programming. They are

  1. Procedural Programming
  2. Object Oriented Programming

What is the entry point to a Kotlin program ? Provide an example.

Like most of the other procedural languages, main() function is the entry point to a Kotlin program.

An Example for main() function is :

Reference – Kotlin main function

Why is Kotlin interoperable with Java?

Kotlin is interoperable with Java because it uses JVM bytecode.  Compiling it directly to bytecode helps to achieve faster compile time and makes no difference between Java and Kotlin for JVM.

Hmm! Where does this Kotlin run ? Does it have some kind of different runtime environment ?

Once compiled, Kotlin programs can run on standard JVM like some other compiled Java code. This means that Kotlin Compiler compiles Kotlin programs to byte-code, which is understood by JVM. So, Kotlin is like a flavor of Java, that goes alongside Java. Interesting fact is that, Kotlin applications can be built with parts of Java code


So, how do you migrate the code from Java to Kotlin ? – Kotlin Interview Question

JetBrains IDEA provides inbuilt tools to convert Java code to Kotlin code. Then you may do the magic offered by Kotlin at some of the parts in code, to make it clean.

Reference – Convert Java File to Kotlin File

Why you should switch to Kotlin from Java?
Kotlin language is quite simple compared to Java. It reduces may redundancies in code as compared to Java. Kotlin can offer some useful features which are not supported by Java.

4) Tell three most important benefits of using Kotlin?

  1. Kotlin language is easy to learn as its syntax is similar to Java.
  2. Kotlin is a functional language and based on JVM. So, it removes lots of boiler plate
  3. It is an expressive language which makes code readable and understandable.

How do Lambda Functions Work in Kotlin?


A lambda function is a small, self-contained block of code that can be passed around your program for greater flexibility. They’re usually written inline and solve basic but frequent programming tasks. We take a closer look at some simple Kotlin lambda functions to understand it in more detail.

fun main(args: Array<String>) {
val greet = { println("Hello!")} // first lambda function 
greet()

val product = { x: Int, y: Int -> x * y } // second lambda function
val result = product(3, 5)
println("Product of two numbers: $result")
}

The first lambda greets the user with the text “Hello” while the second one returns the product of two numbers. Lambda functions are anonymous, meaning they don’t have any names.

Is It Possible to Execute Kotlin Code without JVM?


As we’ve mentioned many times already, Kotlin compiles into bytecode and runs on top of the Java Virtual Machine(JVM). However, it’s also possible to compile Kotlin into native machine code and thus execute successfully without requiring any JVM at all.

Developers can use the Kotlin/Native tool for doing this effortlessly. It’s an effective LLVM backend that allows us to create standalone executables. It exposes some additional functionalities as well. Consult their official documentation for more information.

How do You Create Static Methods in Kotlin?


Static methods are useful for a number of reasons. They allow programmers to prevent the copying of methods and allow working with them without creating an object first. Kotlin doesn’t feature the widely used static keyword found in Java. Rather, you’ll need to create a companion object. Below, we’re comparing the creation of static methods in both Java and Kotlin. Hopefully, they will help you understand them better.

class A {
public static int returnMe() { return 5; } // Java
}

class A {
companion object {
fun a() : Int = 5 // Kotlin
}
}

What is the Purpose of Object Keyword?


Kotlin provides an additional keyword called object alongside its standard object-oriented features. Contrary to the traditional object-oriented paradigm where you define a class and create as many of its instances as you require, the object keyword allows you to create a single, lazy instance. The compiler will create this object when you access it in your Kotlin program. The following program provides a simple illustration.

fun calcRent(normalRent: Int, holidayRent: Int): Unit {
val rates = object{
var normal: Int = 30 * normalRent
var holiday: Int = 30 * holidayRent
}

val total = rates.normal + rates.holiday
print("Total Rent: $$total")
}

fun main() {
calcRent(10, 2)
}

Write a program of Lambda function: addition of two numbers?

  1. fun main(args: Array<String>){
  2. val myLambda: (Int) -> Unit= {s: Int -> println(s) } //lambda function
  3. addNumber(5,10,myLambda)
  4. }
  5. fun addNumber(a: Int, b: Int, mylambda: (Int) -> Unit ){ //high level function lambda as parameter
  6. val add = a + b
  7. mylambda(add) // println(add)
  8. }

Output:
15

Write about Kotlin Architecture?

Kotlin compiler will work differently, whenever it is targeting different another kind of languages such as Java and JavaScript. Kotlin compiler creates a byte code and that byte code can run on the JVM, it is exactly equal to the byte code generated by the Java .class file.

kotlin-architecture

 

Why there is a need for Kotlin Coroutines?

When we call the fetchAndShowUser function, it will throw the NetworkOnMainThreadException as the network call is not allowed on the main thread.

Example

  1. fun fetchUser(): User {
  2. // make network call
  3. // return user
  4. }
  5. fun showUser(user: User) {
  6. // show user
  7. }
  8. fun fetchAndShowUser() {
  9. val user = fetchUser()
  10. showUser(user)
  11. }


What are Coroutines in Kotlin and define?

Coroutines are the lightweight thread in Kotlin that convert async callbacks for long-running tasks, such as a database or network access, into sequential code.

Example

  1. coroutine {
  2. progress.visibility = View.VISIBLE
  3. val user = suspended { userService.doLogin(username, password) }
  4. val currentFriends = suspended { userService.requestCurrentFriends(user) }
  5. val finalUser = user.copy(friends = currentFriends)
  6. toast("User ${finalUser.name} has ${finalUser.friends.size} friends")
  7. progress.visibility = View.GONE
  8. }

Aaaaaa

Comments