Kotlin Interview Vragen

Kotlin is de nieuwste JVM-programmeertaal van JetBrains. Google heeft het samen met Java tot de officiële taal voor Android-ontwikkeling gemaakt. Ontwikkelaars zeggen dat het de problemen aanpakt die zich voordoen bij het programmeren in Java. Ik heb veel Kotlin-tutorials geschreven en hier geef ik belangrijke Kotlin-interviewvragen.

Kotlin Interviewvragen

Hier geef ik Kotlin-interviewvragen en -antwoorden die je zullen helpen bij je Kotlin-interviews. Deze Kotlin-interviewvragen zijn goed voor zowel beginners als ervaren programmeurs. Er zijn ook programmeervragen om je programmeervaardigheden op te frissen.

  1. Wat is het doelplatform van Kotlin? Hoe is Kotlin-Java-interoperabiliteit mogelijk?

    Het doelplatform van Kotlin is de Java Virtual Machine (JVM). Kotlin is 100% interoperabel met Java omdat beide bij compilatie bytecode produceren. Daarom kan Kotlin-code vanuit Java worden aangeroepen en vice versa.

  2. Hoe declareer je variabelen in Kotlin? Hoe verschilt de declaratie van de Java-tegenhanger?

    Er zijn twee belangrijke verschillen tussen de declaratie van variabelen in Java en Kotlin:

    • Het type declaratie In Java ziet de declaratie er als volgt uit:

      String s = "Java String";
      int x = 10;
      

      In Kotlin ziet de declaratie er als volgt uit:

      val s: String = "Hi"
      var x = 5
      

      In Kotlin begint de declaratie met een val en een var, gevolgd door het optionele type. Kotlin kan automatisch het type detecteren met behulp van type inferentie.

    • Standaardwaarde Het volgende is mogelijk in Java:

      String s:
      

      De volgende variabelendeclaratie in Kotlin is niet geldig.

      val s: String
      
  3. Wat is het verschil tussen de declaraties van val en var? Hoe converteer je een String naar een Int?

    val-variabelen kunnen niet worden gewijzigd. Ze zijn vergelijkbaar met de ‘final’ modifiers in Java. Een var kan opnieuw worden toegewezen. De opnieuw toegewezen waarde moet van hetzelfde gegevenstype zijn.

    fun main(args: Array<String>) {
        val s: String = "Hi"
        var x = 5
        x = "6".toInt()
    }
    

    We gebruiken de toInt()-methode om de String naar een Int te converteren.

  4. Wat is Null Safety en Nullable Types in Kotlin? Wat is de Elvis Operator?

    Kotlin hecht veel belang aan null-veiligheid, wat een aanpak is om de gevreesde Null Pointer Exceptions te voorkomen door het gebruik van nullable types zoals String?, Int?, Float?, enz. Deze fungeren als een wrapper type en kunnen null-waarden bevatten. Een nullable waarde kan niet worden toegevoegd aan een andere nullable of een basiswaarde van een type. Om de basiswaarden op te halen moeten we veilige oproepen gebruiken die de Nullable Types unwrapen. Als bij het unwrapen de waarde null is, kunnen we ervoor kiezen om deze te negeren of in plaats daarvan een standaardwaarde te gebruiken. De Elvis Operator wordt gebruikt om veilig de waarde uit de Nullable te unwrapen. Het wordt gerepresenteerd als ?: boven het nullable type. De waarde aan de rechterkant wordt gebruikt als het nullable type null bevat.

    var str: String?  = "JournalDev.com"
    var newStr = str?: "Standaardwaarde" 
    str = null
    newStr = str?: "Standaardwaarde"
    

  5. Wat is een const? Hoe verschilt het van een val?

    Standaard worden val-eigenschappen ingesteld tijdens runtime. Het toevoegen van een const-modifier aan een val maakt er een compile-time constante van. Een const kan niet worden gebruikt met een var of op zichzelf. Een const is niet van toepassing op een lokale variabele.

  6. Ondersteunt Kotlin het gebruik van primitieve typen zoals int, float, double?

    Op het taalniveau kunnen we de bovengenoemde typen niet gebruiken. Maar de JVM-bytecode die wordt gecompileerd, heeft ze zeker.

  7. Wat is het instappunt van elk Kotlin-programma?

    De functie main is het instappunt van elk Kotlin-programma. In Kotlin kunnen we ervoor kiezen om de hoofdfunctie niet binnen de klasse te schrijven. Bij het compileren sluit de JVM deze impliciet in een klasse in. De strings doorgegeven in de vorm van Array<String> worden gebruikt om de commandoregelargumenten op te halen.

  8. Hoe verschilt !! van ?. bij het uitpakken van de optionele waarden? Is er nog een andere manier om optionele waarden veilig uit te pakken?

    !! wordt gebruikt om het optionele type af te dwingen en de waarde te verkrijgen. Als de teruggegeven waarde null is, leidt dit tot een runtime-crash. Daarom moet de !!-operator alleen worden gebruikt als je er absoluut zeker van bent dat de waarde helemaal niet null zal zijn. Anders krijg je de gevreesde nullpointeruitzondering. Aan de andere kant is ?. een Elvis-operator die een veilige oproep uitvoert. We kunnen de lambda-expressie let gebruiken op de optionele waarde om veilig uit te pakken zoals hieronder wordt getoond. Hier doet de let-expressie een veilige oproep om het optionele type uit te pakken.

  9. Hoe wordt een functie gedeclareerd? Waarom worden Kotlin-functies top-level functies genoemd?

    fun sumOf(a: Int, b: Int): Int{
        return a + b
    }
    

    Het retourtype van een functie wordt gedefinieerd na de :. Functies in Kotlin kunnen worden gedeclareerd aan de bovenkant van het Kotlin-bestand.

  10. Wat is het verschil tussen de == en === operators in Kotlin?

\== is used to compare the values are equal or not. === is used to check if the references are equal or not.
  1. Schrijf de zichtbaarheidsmodificatoren op die beschikbaar zijn in Kotlin. Wat is de standaard zichtbaarheidsmodificator?

-   public
-   internal
-   protected
-   private

`public` is the default visibility modifier.
  1. Compileert de volgende overervingstructuur?

```
class A{
}

class B : A(){

}
```

**NO**. By default classes are final in Kotlin. To make them non-final, you need to add the `open` modifier.

```
open class A{
}

class B : A(){

}
```
  1. Wat zijn de soorten constructors in Kotlin? Hoe verschillen ze van elkaar? Hoe definieer je ze in je klasse?

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.

```
class User(name: String, isAdmin: Boolean){

constructor(name: String, isAdmin: Boolean, age: Int) :this(name, isAdmin)
{
    this.age = age
}

}
```
  1. Wat is een init-blok in Kotlin?

`init` is the initialiser block in Kotlin. It's executed once the primary constructor is instantiated. If you invoke a secondary constructor, then it works after the primary one as it is composed in the chain.
  1. Hoe werkt stringinterpolatie in Kotlin? Leg uit aan de hand van een codefragment.

String interpolation is used to evaluate string templates. We use the symbol $ to add variables inside a string.

```
val name = "Journaldev.com"
val desc = "$name now has Kotlin Interview Questions too. ${name.length}"
```

Using `{}` we can compute an expression too.
  1. Wat is het type van argumenten binnen een constructor?

By default, the constructor arguments are `val` unless explicitly set to `var`.
  1. Is ‘nieuw’ een sleutelwoord in Kotlin? Hoe zou je een object van een klasse instantiëren in Kotlin?

**NO**. Unlike Java, in Kotlin, new isn't a keyword. We can instantiate a class in the following way:

```
class A
var a = A()
val new = A()
```
  1. Wat is het equivalent van een switch-uitdrukking in Kotlin? Hoe verschilt het van switch?

when is the equivalent of `switch` in `Kotlin`. The default statement in a when is represented using the else statement.

```
var num = 10
    when (num) {
        0..4 -> print("value is 0")
        5 -> print("value is 5")
        else -> {
            print("value is in neither of the above.")
        }
    }
```

`when` statments have a default break statement in them.
  1. Wat zijn dataklassen in Kotlin? Wat maakt ze zo nuttig? Hoe worden ze gedefinieerd?

In Java, to create a class that stores data, you need to set the variables, the getters and the setters, override the `toString()`, `hash()` and `copy()` functions. In Kotlin you just need to add the `data` keyword on the class and all of the above would automatically be created under the hood.

```
data class Book(var name: String, var authorName: String)

fun main(args: Array<String>) {
val book = Book("Kotlin Tutorials","Anupam")
}
```

Thus, data classes saves us with lot of code. It creates component functions such as `component1()`.. `componentN()` for each of the variables. [![kotlin interview questions data classes](https://journaldev.nyc3.cdn.digitaloceanspaces.com/2018/04/kotlin-interview-questions-data-classes.png)](https://journaldev.nyc3.cdn.digitaloceanspaces.com/2018/04/kotlin-interview-questions-data-classes.png)
  1. Wat zijn destructureringsverklaringen in Kotlin? Leg het uit met een voorbeeld.

Destructuring Declarations is a smart way to assign multiple values to variables from data stored in objects/arrays. [![kotlin interview questions destructuring declarations](https://journaldev.nyc3.cdn.digitaloceanspaces.com/2018/04/kotlin-interview-questions-destructuring-declarations.png)](https://journaldev.nyc3.cdn.digitaloceanspaces.com/2018/04/kotlin-interview-questions-destructuring-declarations.png) Within paratheses, we've set the variable declarations. Under the hood, destructuring declarations create component functions for each of the class variables.
  1. Wat is het verschil tussen inline- en infix-functies? Geef van elk een voorbeeld.

[Inline functions](/community/tutorials/kotlin-inline-function-reified) are used to save us memory overhead by preventing object allocations for the anonymous functions/lambda expressions called. Instead, it provides that functions body to the function that calls it at runtime. This increases the bytecode size slightly but saves us a lot of memory. [![kotlin interview questions inline functions](https://journaldev.nyc3.cdn.digitaloceanspaces.com/2018/04/kotlin-interview-questions-inline-functions.png)](https://journaldev.nyc3.cdn.digitaloceanspaces.com/2018/04/kotlin-interview-questions-inline-functions.png) [infix functions](/community/tutorials/kotlin-functions) on the other are used to call functions without parentheses or brackets. Doing so, the code looks much more like a natural language. [![kotlin interview questions infix notations](https://journaldev.nyc3.cdn.digitaloceanspaces.com/2018/04/kotlin-interview-questions-infix-notations.png)](https://journaldev.nyc3.cdn.digitaloceanspaces.com/2018/04/kotlin-interview-questions-infix-notations.png)
  1. Wat is het verschil tussen lazy en lateinit?

Both are used to delay the property initializations in Kotlin `lateinit` is a modifier used with var and is used to set the value to the var at a later point. `lazy` is a method or rather say lambda expression. It's set on a val only. The val would be created at runtime when it's required.

```
val x: Int by lazy { 10 }
lateinit var y: String
```
  1. Hoe maak je Singleton-klassen?

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.
  1. Heeft Kotlin het static-woord? Hoe maak je statische methoden 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()`.
  1. Wat is het type van de volgende Array?

```
val arr = arrayOf(1, 2, 3);
```

The type is Array<Int>.

Dat is alles voor Kotlin sollicitatievragen en antwoorden.

Source:
https://www.digitalocean.com/community/tutorials/kotlin-interview-questions