Kotlin 面试问题

Kotlin是一种最新的JVM编程语言,由JetBrains推出。谷歌将其与Java一同设定为Android开发的官方语言。开发者表示,它解决了Java编程中所遇到的问题。我写了很多关于Kotlin的教程,这里我将提供一些重要的Kotlin面试问题。

Kotlin面试问题

在这里,我提供了一些 Kotlin 面试问题和答案,这将帮助你准备 Kotlin 面试。 这些 Kotlin 面试问题适用于初学者和有经验的程序员。还有编程问题,可以帮助你提升编码能力。

    1. Kotlin中KotlinJVM是目标平台。由于Java虚拟机(JVM)是Kotlin的目标平台,因此Kotlin与Java具有100%的互操作性。编译后都会生成字节码,所以可以从Java调用Kotlin代码,反之亦然。

在Kotlin中,变量的声明有两个主要区别与Java:

1. 声明的类型。在Java中,声明如下:
String s = “Java String”;
int x = 10;

在Kotlin中,声明如下:
val s: String = “Hi”
var x = 5

Kotlin的声明以val和var开始,之后是可选的类型。Kotlin可以使用类型推断自动检测类型。

2. 默认值。在Java中,可以使用如下方式:
String s;

在Kotlin中,以下变量声明是无效的:
val s: String

val变量是不可变的,类似于Java中的final修饰符。var变量可以重新赋值,但重新赋值的值必须是相同的数据类型。我们使用toInt()方法将String转换为Int。

Kotlin非常注重空安全,该特性用于防止令人恶心的空指针异常。Kotlin使用可空类型(例如String?、Int?、Float?等)来实现空安全。可空类型起到了包装类型的作用,可以包含null值。可空值不能添加到另一个可空值或基本类型值中。要获取基本类型值,我们需要使用安全调用来取消包装可空类型。如果在取消包装时,值为null,我们可以选择忽略或使用默认值。Elvis运算符用于安全取消包装Nullable值,表示为?:。如果Nullable类型为null,则使用右侧的值。

const是编译时常量,val属性默认是在运行时设置的。const不能与var一起使用,也不能单独使用。const不适用于局部变量。

在语言级别,Kotlin不允许直接使用int、float、double等原始类型。但是,编译生成的JVM字节码确实包含这些类型。

每个Kotlin程序的入口点是main函数。在Kotlin中,我们可以选择不在类中编写main函数。在编译时,JVM会隐式封装它在一个类中。以Array形式传递的字符串用于检索命令行参数。

!!用于强制取消包装可空类型以获取值。如果返回的值为null,将导致运行时错误。因此,!!操作符只应在确定值绝对不会为null时使用。否则,将会出现令人恐怖的空指针异常。另一方面,?.是Elvis运算符,用于进行安全调用。我们可以使用lambda表达式let来安全取消包装可空类型。这里的let表达式对可空类型进行安全调用解除包装。

函数的声明如下所示:
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.
    列出 Kotlin 中可用的可见性修饰符。默认的可见性修饰符是什么?
-   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(){

}
```
    在Kotlin中有哪些构造函数类型?它们有何不同?如何在类中定义它们?
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
}

}
```
    Kotlin中的init块是什么意思?
`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.
    在Kotlin中,字符串插值是如何工作的?请用一段代码片段解释一下。
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`.
    在Kotlin中,”new”是一个关键字吗?你如何在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()
```
    在Kotlin中,switch表达式的等价语法是什么?它与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.
    在Kotlin中,数据类是什么?它们有什么用处?它们是如何定义的?
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://scdev.nyc3.cdn.digitaloceanspaces.com/2018/04/kotlin-interview-questions-data-classes.png)](https://scdev.nyc3.cdn.digitaloceanspaces.com/2018/04/kotlin-interview-questions-data-classes.png)
    请用一个例子来解释一下Kotlin中的解构声明是什么意思。
Destructuring Declarations is a smart way to assign multiple values to variables from data stored in objects/arrays. [![kotlin interview questions destructuring declarations](https://scdev.nyc3.cdn.digitaloceanspaces.com/2018/04/kotlin-interview-questions-destructuring-declarations.png)](https://scdev.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. [![kotlin interview questions inline functions](https://scdev.nyc3.cdn.digitaloceanspaces.com/2018/04/kotlin-interview-questions-inline-functions.png)](https://scdev.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://scdev.nyc3.cdn.digitaloceanspaces.com/2018/04/kotlin-interview-questions-infix-notations.png)](https://scdev.nyc3.cdn.digitaloceanspaces.com/2018/04/kotlin-interview-questions-infix-notations.png)
    「懒加载(lazy)」和「延迟加载(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
```
    如何创建单例类?
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.
    Kotlin有静态关键字吗?如何在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()`.
    以下数组的类型是什么?
```
val arr = arrayOf(1, 2, 3);
```

The type is Array<Int>.

这就是关于Kotlin面试问题和答案的全部内容。

广告
将在 10 秒后关闭
bannerAds