Kotlin是由JetBrains推出的最新JVM編程語言。谷歌已將其與Java一起成為Android開發的官方語言。開發者表示,它解決了Java編程中遇到的問題。我寫了很多Kotlin教程,在這裡我提供了重要的Kotlin面試問題。
Kotlin面試問題
在這裡,我提供了Kotlin面試問題和答案,這將幫助你應對Kotlin面試。這些Kotlin面試問題對於初學者和有經驗的程序員都很有用。也有一些編程問題可以幫助你提高編程技能。
-
Kotlin的目標平台是什麼? Kotlin-Java互操作性是如何實現的?
Java虛擬機(JVM)是Kotlin的目標平台。由於它們都能生成字節碼,因此Kotlin與Java是100%可互操作的。因此,Kotlin代碼可以從Java調用,反之亦然。
-
在 Kotlin 中如何聲明變量?聲明與 Java 的對應有何不同?
Java 和 Kotlin 變量聲明有兩個主要區別:
-
聲明的類型 在 Java 中,聲明如下:
String s = "Java String"; int x = 10;
在 Kotlin 中,聲明如下:
val s: String = "Hi" var x = 5
在 Kotlin 中,聲明以
val
和var
開頭,後跟可選類型。Kotlin 可以使用類型推斷自動檢測類型。 -
默認值 在 Java 中,以下操作是可能的:
String s:
在 Kotlin 中,以下變量聲明無效。
val s: String
-
-
val 和 var 声明有什么区别?如何将字符串转换为整数?
val
变量无法更改。它们类似于 Java 中的 final 修饰符。var
可以被重新赋值。重新赋值的值必须是相同的数据类型。fun main(args: Array<String>) { val s: String = "Hi" var x = 5 x = "6".toInt() }
我们使用
toInt()
方法将字符串转换为整数。 -
在 Kotlin 中,什麼是 Null 安全性和可為空類型?什麼是 Elvis 運算子?
Kotlin非常重視空安全性,這是一種避免可怕的空指針異常的方法,它使用可為空類型,例如
String?
、Int?
、Float?
等。這些類型作為包裝類型,可以保存空值。可為空值不能添加到另一個可為空或基本類型的值中。要檢索基本類型,我們需要使用安全調用來取消包裝可為空類型。如果在取消包裝時,值為空,我們可以選擇忽略或使用默認值。Elvis 運算子用於安全地從可為空中取消包裝值。它表示為?:
,右邊的值將在可為空類型為空時使用。var str: String? = "JournalDev.com" var newStr = str?: "Default Value" str = null newStr = str?: "Default Value"
-
什麼是
const
?它與val
有什麼不同?默認情況下,
val
屬性在運行時設置。在val
上添加 const 修飾符會使其成為編譯時常數。const
不能與var
一起使用,也不能單獨使用。const
不適用於局部變數。 -
Kotlin 是否允許我們使用像 int、float、double 這樣的原始類型?
在語言層面上,我們不能使用上述類型。但編譯後的 JVM 字節碼確實包含它們。
-
每個 Kotlin 程序的入口點是什麼?
main
函數是每個 Kotlin 程序的入口點。在 Kotlin 中,我們可以選擇不在類內部編寫 main 函數。在編譯時,JVM 隱式將其封裝在一個類中。以Array<String>
形式傳遞的字符串用於檢索命令行參數。 -
在解開可空值方面,
!!
和?有什麼不同嗎?還有其他安全解開可空值的方式嗎?!!
用於強制解開可空類型以獲取值。如果返回的值為空,將導致運行時崩潰。因此,!!
運算符只應在您絕對確定值絕對不為空時使用。否則,您將遇到可怕的空指針異常。另一方面,?是一個艾維斯運算符,它執行安全調用。我們可以在可空值上使用lambda表達式let
來安全解開,如下所示。在這裡,let表達式對可空類型進行安全調用。
-
如何宣告函數?為什麼 Kotlin 函數被稱為頂級函數?
fun sumOf(a: Int, b: Int): Int{ return a + b }
在
:
後定義函數的返回類型。Kotlin 中的函數可以在 Kotlin 檔案的根部宣告。 -
在 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>.
這就是有關Kotlin面試問題和答案的全部。
Source:
https://www.digitalocean.com/community/tutorials/kotlin-interview-questions