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.
-
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.
-
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 eenvar
, 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
-
-
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. Eenvar
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. -
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"
-
Wat is een
const
? Hoe verschilt het van eenval
?Standaard worden
val
-eigenschappen ingesteld tijdens runtime. Het toevoegen van een const-modifier aan eenval
maakt er een compile-time constante van. Eenconst
kan niet worden gebruikt met eenvar
of op zichzelf. Eenconst
is niet van toepassing op een lokale variabele. -
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.
-
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 vanArray<String>
worden gebruikt om de commandoregelargumenten op te halen. -
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-expressielet
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.
-
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. -
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.
- public
- internal
- protected
- private
`public` is the default visibility modifier.
```
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(){
}
```
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
}
}
```
`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.
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.
By default, the constructor arguments are `val` unless explicitly set to `var`.
**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()
```
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.
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. [](https://journaldev.nyc3.cdn.digitaloceanspaces.com/2018/04/kotlin-interview-questions-data-classes.png)
Destructuring Declarations is a smart way to assign multiple values to variables from data stored in objects/arrays. [](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.
[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. [](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. [](https://journaldev.nyc3.cdn.digitaloceanspaces.com/2018/04/kotlin-interview-questions-infix-notations.png)
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
```
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.
**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()`.
```
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