Monday, April 20, 2020

Kotlin - Interview Questions and Answers

kotlin interview questions and answer
Kotlin is a cross-platform,  general-purpose, and statically typed programming language. Kotlin is designed to interoperate fully with Java, and the JVM version of its standard library that is depends on the Java Class Library. Here, I'm going to share the comprehensive collection of the most common and advanced Kotlin Interview Questions every Android or Kotlin developer should know.

1. How to initialize an array in Kotlin with values?
  • Java:
     int numbers[] = new int[] {10, 20, 30, 40, 50}
  • Kotlin
    val numbers: IntArray = intArrayOf(10, 20, 30, 40, 50) 

2. What is the basic difference between fold and reduce in Kotlin?
  • fold: This function accumulates value with the initial value. After that apply the operation from left to right to current accumulator value and each element.
    fun main() {
       var value= listOf(1, 2, 3).fold(2) { sum, element -> sum * element }
       println(value)
    }
    
    Answer: 12
  • reduce accumulates value from the first element and apply operations from left to right to current accumulator value and each element.

    fun main() {
        
       var value= listOf(1, 2, 3,4,5,6).reduce { sum, element -> sum + element }
       println(value)
    }
    
    Answer: 21
    /* Process
      sum= 1, element = 2
      sum= 3, element = 3
      sum= 6, element = 4
      sum= 10, element = 5
      sum= 15, element = 6
      21
    */

3. What is the difference between var and val in Kotlin?
  • Var

    var can be assigned multiple times that's why it is known as the mutable variable in Kotlin.
    var v1 = 10
    v1 = 30 //works fine
  • Val

    val is a constant or final variable that can not be assigned multiple times. It can be Initialized only once that's why it is known as the immutable variable in Kotlin. It means once the value is assigned to val variable. It can’t be changed later.
    val v2 = 10
    v2 = 30 //it will show error, "Val cannot be reassigned"

4. What is a data class in Kotlin?
  • A data class is a class that only contains state. It does not perform any operation. 
  • The data class provides self-generated code(1. equals(),  2. hashCode(),  3. toString(),  4. copy(),  5. componentN() ).
  • It avoids getters and setters boilerplate code.

Kotlin Data Class Requirements

To make a class as data, we have to follow the following principles:
1. The primary constructor must have at least one parameter and the parameters are either marked val or var.
2. The class cannot be marked as abstract
, open, sealed or inner.
3. The data class can extend (inherit) other class and it can also implement other interfaces.



5. How to create a singleton class in Kotlin?
  • We create a Singleton class with the help object keyword only in Kotlin. It can be defined without the use of a class. 
  • An object class contains properties, functions, and the init method.
    object Singleton
    {
    
        init {
            println("Singleton class ")
        }
        var name = "www.developerlibs.com"
        fun printName()
        {
            println(name)
        }
    
    }



6. Explain lateinit and lazy?

  • lateinit

    The modifier lateinit allows the compiler to delay the initialization of a variable. The compiler recognizes that the value of the non-null property is not stored in the constructor stage to compile normally. It can be applied to the var properties only because it can’t be compiled to a final field. We have to be careful to assign our lateinit var properties before we use it. Otherwise, it will crash the app on a null value.
    public class Devloper {
    
         lateinit var libs: Libs
    
         fun create() {
           libs = Libs()
         }
    
         fun Libs() {
           libs.do()
         }
    }

  • lazy

    A lazy property is initialized when it is used for the first time. The value of lazy property computes only one thread, and all threads can use the same value. The lazy property gets initializations when you first-time access the lazy property. For the second time, this value is remembered and returned. It can only be used with the val properties:
    val myName by lazy {
        println("developerlisb")            
        "www.developerlibs.com"       
    }
    fun main(args: Array<String>) {
        println(myName)    //it'll print developerlibs and www.developerlibs.com
        println(myName)   // only stored value www.developerlibs.com
    }
    
    Ans:
    
    developerlisb
    www.developerlibs.com
    www.developerlibs.com

7. Explain the Null safety in Kotlin?
  • The type system of Kotlin distinguishes the references that can hold null (nullable references) and those that can not (non-null references). The compiler gives information about the correctness of a program at compile time. For example, a regular String type variable can not hold null:
    var name: String = "developerlibs"
    name = null // compilation error

    we can declare a variable as a nullable string:
    var name: String? = "developerlibs"
    name = null // ok
    print(name)

    Null Safety can eliminate the risk of occurrence of NPE in real-time because Kotlin can detect NPE exception errors at compile time itself and guard against them. Read more about Null safety

8. Can we declare the properties of the class inside of the secondary constructor?
  • No, we can not declare the property of the class inside the secondary constructor. As you see below code snippet that'll give an error if you compile it. Because, we are declaring a property id of the class in the secondary constructor, which is not allowed in Kotlin:
    class Student (var name: String) {
        init() {
            println("Student has got a name as $name")
        }
        constructor(sectionName: String, var id: Int) this(sectionName) {
        }
    }
    You can use property inside the secondary constructor if declared the property inside the class and use it in the secondary constructor:
    class Student (var name: String) {
        var id: Int = -1
        init() {
            println("Student has got a name as $name")
        }
        constructor(secname: String, id: Int) this(secname) {
            this.id = id
        }
    }



.
.
.
Share:

Youtube

We're Social

Android - Expandable Listview inside scrollview

In Android application, if you want to show items in a list with expandable feature. The ExpandableListView is a option that show items in a...