Kotlin é a mais recente linguagem de programação JVM da JetBrains. O Google a tornou a linguagem oficial para o Desenvolvimento Android, juntamente com o Java. Os desenvolvedores afirmam que ela aborda os problemas enfrentados na programação Java. Eu escrevi muitos tutoriais de Kotlin e aqui estou fornecendo perguntas importantes de entrevista sobre Kotlin.
Perguntas de Entrevista sobre Kotlin
Aqui estou fornecendo perguntas e respostas de entrevista sobre Kotlin que o ajudarão em suas entrevistas de Kotlin. Essas perguntas de entrevista sobre Kotlin são boas tanto para iniciantes quanto para programadores experientes. Também existem perguntas de codificação para melhorar suas habilidades de codificação.
-
Qual é a Plataforma Alvo do Kotlin? Como é possível a interoperabilidade Kotlin-Java?
A Plataforma Alvo do Kotlin é a Java Virtual Machine (JVM). Kotlin é 100% interoperável com Java, uma vez que ambas, na compilação, produzem bytecode. Portanto, o código Kotlin pode ser chamado a partir de Java e vice-versa.
-
Como se declaram variáveis em Kotlin? Como difere a declaração do equivalente em Java?
Há duas diferenças principais entre a declaração de variáveis em Java e Kotlin:
-
O tipo de declaração Em Java, a declaração é assim:
String s = "Java String"; int x = 10;
Em Kotlin, a declaração é assim:
val s: String = "Oi" var x = 5
Em Kotlin, a declaração começa com um
val
e umvar
seguido do tipo opcional. Kotlin pode detectar automaticamente o tipo usando inferência de tipo. -
Valor padrão O seguinte é possível em Java:
String s:
A seguinte declaração de variável em Kotlin não é válida.
val s: String
-
-
Qual é a diferença entre declaração de val e var? Como converter uma String para um Int?
As variáveis
val
não podem ser alteradas. São como modificadores finais em Java. Umvar
pode ser reatribuído. O valor reatribuído deve ser do mesmo tipo de dados.fun main(args: Array<String>) { val s: String = "Oi" var x = 5 x = "6".toInt() }
Nós usamos o método
toInt()
para converter a String para um Int. -
O que é Null Safety e Tipos Nullable em Kotlin? O que é o Operador Elvis?
O Kotlin dá grande importância à segurança nula, que é uma abordagem para evitar as temidas exceções de ponteiro nulo, usando tipos nulos como
String?
,Int?
,Float?
, etc. Estes atuam como um tipo de invólucro e podem conter valores nulos. Um valor nulo não pode ser adicionado a outro valor nulo ou a um tipo básico de valor. Para recuperar os tipos básicos, precisamos usar chamadas seguras que desempacotam os Tipos Nullable. Se, ao desempacotar, o valor for nulo, podemos optar por ignorá-lo ou usar um valor padrão. O Operador Elvis é usado para desempacotar com segurança o valor do Nullable. É representado como?:
sobre o tipo nulo. O valor do lado direito seria usado se o tipo nulo contiver um nulo.var str: String? = "JournalDev.com" var newStr = str?: "Valor Padrão" str = null newStr = str?: "Valor Padrão"
-
O que é um
const
? Como difere de umval
?Por padrão, as propriedades
val
são definidas em tempo de execução. Adicionar um modificador const em umval
faria dele uma constante em tempo de compilação. Umconst
não pode ser usado com umvar
ou por si só. Umconst
não é aplicável em uma variável local. -
O Kotlin permite o uso de tipos primitivos como int, float e double?
No nível da linguagem, não podemos usar os tipos mencionados acima. No entanto, o bytecode JVM compilado certamente os inclui.
-
Qual é o ponto de entrada de todo Programa Kotlin?
A função
main
é o ponto de entrada de todo programa Kotlin. Em Kotlin, podemos optar por não escrever a função main dentro da classe. Ao compilar, a JVM encapsula implicitamente dentro de uma classe. As strings passadas na forma deArray<String>
são usadas para recuperar os argumentos da linha de comando. -
Como é que
!!
é diferente de ?. ao desembrulhar os valores nulos? Existe alguma outra maneira de desembrulhar valores nulos com segurança?!!
é usado para forçar o desembrulho do tipo nulo para obter o valor. Se o valor retornado for nulo, isso levará a uma falha em tempo de execução. Portanto, o operador!!
deve ser usado apenas quando você tem absoluta certeza de que o valor não será nulo. Caso contrário, você terá a temida exceção de ponteiro nulo. Por outro lado, o ?. é um Operador Elvis que faz uma chamada segura. Podemos usar a expressão lambdalet
no valor nulo para desembrulhar com segurança, como mostrado abaixo.Aqui, a expressão let faz uma chamada segura para desembrulhar o tipo nulo.
-
Como uma função é declarada? Por que as funções em Kotlin são conhecidas como funções de nível superior?
fun somaDe(a: Int, b: Int): Int{ return a + b }
O tipo de retorno de uma função é definido após o
:
Funções em Kotlin podem ser declaradas na raiz do arquivo Kotlin. -
Qual é a diferença entre os operadores == e === em 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>.
Isso é tudo para perguntas e respostas de entrevista sobre Kotlin.
Source:
https://www.digitalocean.com/community/tutorials/kotlin-interview-questions