Kotlin Interview Fragen

Kotlin ist die neueste JVM-Programmiersprache von JetBrains. Google hat sie zusammen mit Java zur offiziellen Sprache für die Android-Entwicklung gemacht. Entwickler sagen, dass sie die Probleme in der Java-Programmierung angeht. Ich habe viele Kotlin-Tutorials geschrieben, und hier stelle ich wichtige Kotlin-Interviewfragen bereit.

Kotlin Interviewfragen

Hier stelle ich Kotlin-Interviewfragen und -Antworten bereit, die Ihnen bei Ihren Kotlin-Interviews helfen werden. Diese Kotlin-Interviewfragen sind sowohl für Anfänger als auch für erfahrene Programmierer geeignet. Es gibt auch Codierungsfragen, um Ihre Codierungskenntnisse aufzufrischen.

  1. Was ist die Zielplattform von Kotlin? Wie ist die Kotlin-Java-Interoperabilität möglich?

    Die Zielplattform von Kotlin ist die Java Virtual Machine (JVM). Kotlin ist zu 100 % interoperabel mit Java, da beide bei der Kompilierung Bytecode erzeugen. Daher kann Kotlin-Code aus Java aufgerufen werden und umgekehrt.

  2. Wie deklariert man Variablen in Kotlin? Wie unterscheidet sich die Deklaration von der Java-Gegenstück?

    Es gibt zwei wesentliche Unterschiede zwischen der Variablendeklaration in Java und Kotlin:

    • Der Typ der Deklaration In Java sieht die Deklaration so aus:

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

      In Kotlin sieht die Deklaration so aus:

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

      In Kotlin beginnt die Deklaration mit einem val oder var gefolgt vom optionalen Typ. Kotlin kann den Typ automatisch mithilfe von Typinferenz erkennen.

    • Standardwert In Java ist Folgendes möglich:

      String s:
      

      Die folgende Variablendeklaration in Kotlin ist nicht gültig.

      val s: String
      
  3. Was ist der Unterschied zwischen einer val- und var-Deklaration? Wie konvertiert man einen String in ein Int?

    val-Variablen können nicht geändert werden. Sie sind ähnlich wie die final-Modifier in Java. Eine var-Variable kann neu zugewiesen werden. Der neu zugewiesene Wert muss vom gleichen Datentyp sein.

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

    Wir verwenden die toInt()-Methode, um den String in ein Int zu konvertieren.

  4. Was ist Null Safety und Nullable Types in Kotlin? Was ist der Elvis Operator?

    Kotlin legt großen Wert auf Null-Sicherheit, was einen Ansatz darstellt, um die gefürchteten Null Pointer Exceptions zu verhindern. Dies wird durch die Verwendung von Nullable Types erreicht, die wie String?, Int?, Float? usw. sind. Diese fungieren als Wrapper-Typ und können Nullwerte enthalten. Ein Nullable-Wert kann nicht zu einem anderen Nullable- oder Basiswert hinzugefügt werden. Um die Grundtypen abzurufen, müssen wir sichere Aufrufe verwenden, die die Nullable Types entpacken. Wenn beim Entpacken der Wert null ist, können wir wählen, ob wir ihn ignorieren oder stattdessen einen Standardwert verwenden möchten. Der Elvis Operator wird verwendet, um den Wert sicher aus dem Nullable zu entpacken. Er wird als ?: über dem nullable Typ dargestellt. Der Wert auf der rechten Seite wird verwendet, wenn der nullable Typ ein null enthält.

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

  5. Was ist ein const? Wie unterscheidet es sich von einem val?

    Standardmäßig werden val-Eigenschaften zur Laufzeit festgelegt. Das Hinzufügen eines const-Modifiers zu einem val würde es zu einer Kompilierzeitkonstanten machen. Ein const kann nicht mit einem var verwendet werden oder allein stehen. Ein const ist nicht anwendbar auf eine lokale Variable.

  6. Erlaubt Kotlin uns, primitive Typen wie int, float, double zu verwenden?

    Auf der Sprachebene können wir die oben genannten Typen nicht verwenden. Aber der JVM-Bytecode, der kompiliert wird, hat sie sicherlich.

  7. Was ist der Einstiegspunkt jedes Kotlin-Programms?

    Die main-Funktion ist der Einstiegspunkt jedes Kotlin-Programms. In Kotlin können wir wählen, die main-Funktion nicht innerhalb der Klasse zu schreiben. Beim Kompilieren kapselt die JVM sie implizit in einer Klasse ein. Die übergebenen Zeichenfolgen in Form von Array<String> werden verwendet, um die Befehlszeilenargumente abzurufen.

  8. Wie unterscheidet sich !! von ?. beim Auspacken der Nullwerte? Gibt es eine andere Möglichkeit, Nullwerte sicher auszupacken?

    !! wird verwendet, um den Nulltyp erzwingend auszupacken, um den Wert zu erhalten. Wenn der zurückgegebene Wert null ist, führt dies zu einem Laufzeitfehler. Daher sollte der !!-Operator nur verwendet werden, wenn Sie absolut sicher sind, dass der Wert überhaupt nicht null ist. Andernfalls erhalten Sie die gefürchtete Nullzeigerausnahme. Auf der anderen Seite ist ein ?. ein Elvis-Operator, der einen sicheren Aufruf durchführt. Wir können den Lambda-Ausdruck let auf den Nullwert anwenden, um sicher auszupacken, wie unten gezeigt. Hier führt der let-Ausdruck einen sicheren Aufruf zum Auspacken des Nulltyps durch.

  9. Wie wird eine Funktion deklariert? Warum werden Kotlin-Funktionen als Top-Level-Funktionen bezeichnet?

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

    Der Rückgabetyp einer Funktion wird nach dem : definiert. Funktionen in Kotlin können an der Wurzel der Kotlin-Datei deklariert werden.

  10. Was ist der Unterschied zwischen den Operatoren == und === in Kotlin?

\== is used to compare the values are equal or not. === is used to check if the references are equal or not.
  1. Auflistung der Sichtbarkeitsmodifikatoren in Kotlin. Was ist der Standard-Sichtbarkeitsmodifikator?

-   public
-   internal
-   protected
-   private

`public` is the default visibility modifier.
  1. Kompiliert die folgende Vererbungsstruktur?

```
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. Was sind die Arten von Konstruktoren in Kotlin? Wie unterscheiden sie sich? Wie definiert man sie in deiner 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. Was ist der init-Block 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. Wie funktioniert die String-Interpolation in Kotlin? Erläutern Sie dies anhand eines Code-Snippets.

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. Welche Art von Argumenten werden innerhalb eines Konstruktors verwendet?

By default, the constructor arguments are `val` unless explicitly set to `var`.
  1. Ist „new“ ein Schlüsselwort in Kotlin? Wie instanziieren Sie ein Objekt einer Klasse 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. Was ist das Äquivalent des Switch-Ausdrucks in Kotlin? Wie unterscheidet es sich von 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. Was sind Datenklassen in Kotlin? Was macht sie so nützlich? Wie werden sie definiert?

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. Was sind Destrukturierungserklärungen in Kotlin? Erklären Sie es mit einem Beispiel.

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. Was ist der Unterschied zwischen Inline- und Infix-Funktionen? Geben Sie jeweils ein Beispiel.

[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. Was ist der Unterschied zwischen Lazy und 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. Wie erstellt man 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. Hat Kotlin das statische Schlüsselwort? Wie erstellt man 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. Welchen Typ hat das folgende Array?

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

The type is Array<Int>.

Das war alles für Kotlin-Interviewfragen und -antworten.

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