kotlin面试
Kotlin is the latest JVM programming language from the JetBrains. Google has made it the official language for Android Development along with Java. Developers say it addresses the issues faced in Java programming. I have written a lot of Kotlin tutorials and here I am providing important kotlin interview questions.
Kotlin是JetBrains中最新的JVM编程语言。 Google使其与Java一起成为Android开发的官方语言。 开发人员说,它解决了Java编程面临的问题。 我写了很多Kotlin教程,在这里我提供了重要的Kotlin面试问题。
Here I am providing Kotlin Interview Questions and Answers that will help you in your Kotlin Interviews. These Kotlin interview questions are good for beginners as well as experienced programmers. There are coding questions too to brush up your coding skills.
在这里,我提供了Kotlin面试问答,可以帮助您进行Kotlin面试。 这些Kotlin面试问题对初学者和经验丰富的程序员都非常有用。 还有一些编码问题可以提高您的编码技能。
Java Virtual Machine(JVM) is the Target Platform of Kotlin. Kotlin is 100% interoperable with Java since both, on compilation produce bytecode. Hence Kotlin code can be called from Java and vice-versa.
Java虚拟机(JVM)是Kotlin的目标平台。 Kotlin可与Java 100%互操作,因为两者在编译时都会产生字节码。 因此,可以从Java调用Kotlin代码,反之亦然。
There are two major differences between Java and Kotlin variable declaration:
String s = "Java String";
int x = 10;
In Kotlin the declaration looks like:
In Kotlin, the declaration begins with a val
and a var
followed by the optional type. Kotlin can automatically detect the type using type inference.
String s:
The following variable declaration in Kotlin is not valid.
Java和Kotlin变量声明之间有两个主要区别:
String s = "Java String";
int x = 10;
在Kotlin中,声明如下所示:
在Kotlin中,声明以val
和var
开头,后跟可选类型。 Kotlin可以使用类型推断自动检测类型。
String s:
Kotlin中的以下变量声明无效。
val
variables cannot be changed. They’re like final modifiers in Java. A var
can be reassigned. The reassigned value must be of the same data type.
fun main(args: Array) {
val s: String = "Hi"
var x = 5
x = "6".toInt()
}
We use the toInt()
method to convert the String to an Int.
val
变量不能更改。 它们就像Java中的最终修饰符。 可以重新分配var
。 重新分配的值必须具有相同的数据类型。
我们使用toInt()
方法将String转换为Int。
Kotlin puts a lot of weight behind null safety which is an approach to prevent the dreaded Null Pointer Exceptions by using nullable types which are like String?
, Int?
, Float?
etc. These act as a wrapper type and can hold null values. A nullable value cannot be added to another nullable or basic type of value.
To retrieve the basic types we need to use safe calls that unwrap the Nullable Types. If on unwrapping, the value is null we can choose to ignore or use a default value instead. The Elvis Operator is used to safely unwrap the value from the Nullable.
It’s represented as ?:
over the nullable type. The value on the right hand side would be used if the nullable type holds a null.
var str: String? = "JournalDev.com"
var newStr = str?: "Default Value"
str = null
newStr = str?: "Default Value"
Kotlin在null安全性后面放了很多权重,这是通过使用像String?
这样的nullable类型来防止可怕的Null Pointer异常的一种方法String?
, Int?
, Float?
等等。它们充当包装器类型,可以容纳空值。 无法将可为空的值添加到其他可为空或基本类型的值中。
要检索基本类型,我们需要使用安全的调用来拆开可空类型。 如果展开,则该值为null,我们可以选择忽略或使用默认值。 Elvis运算符用于安全地将值从Nullable中解包。
它在可为空的类型上表示为?:
。 如果可为空的类型为null,则将使用右侧的值。
var str: String? = "JournalDev.com"
var newStr = str?: "Default Value"
str = null
newStr = str?: "Default Value"
const
? 它与val
有何不同? (What’s a const
? How does it differ from a val
?)By default val
properties are set at runtime. Adding a const modifier on a val
would make a compile-time constant.
A const
cannot be used with a var
or on its own.
A const
is not applicable on a local variable.
默认情况下, val
属性在运行时设置。 在val
上添加const修饰符将使编译时常数。
const
不能与var
一起使用,也不能单独使用。
const
不适用于局部变量。
At the language level, we cannot use the above-mentioned types. But the JVM bytecode that’s compiled does certainly have them.
在语言级别,我们不能使用上述类型。 但是,已编译的JVM字节码确实具有它们。
The main
function is the entry point of every Kotlin program. In Kotlin we can choose not to write the main function inside the class. On compiling the JVM implicitly encapsulates it in a class.
The strings passed in the form of Array
are used to retrieve the command line arguments.
main
功能是每个Kotlin程序的入口。 在Kotlin中,我们可以选择不在类内部编写main函数。 编译JVM时会将其隐式封装在一个类中。
以Array
形式传递的Array
用于检索命令行参数。
!!
不同于 ?。 在展开可为空的值? 还有其他方法可以安全地包装可空值吗? (How is !!
different from ?. in unwrapping the nullable values? Is there any other way to unwrap nullable values safely?)!!
is used to force unwrap the nullable type to get the value. If the value returned is a null, it would lead to a runtime crash. Hence a !!
operator should be only used when you’re absolutely sure that the value won’t be null at all. Otherwise, you’ll get the dreaded null pointer exception. On the other hand, a ?. is an Elvis Operator that does a safe call.
We can use the lambda expression let
on the nullable value to unwrap safely as shown below.
!!
用于强制拆开可为null的类型以获取值。 如果返回的值为null,则将导致运行时崩溃。 因此!!
仅在绝对确定该值不会为null时,才应使用operator。 否则,您将得到可怕的空指针异常。 另一方面,?。 是负责安全呼叫的猫王操作员。
我们可以使用lambda表达式let
对空值如下图所示安全解开。
在这里,let表达式进行安全调用以解开可为空的类型。
fun sumOf(a: Int, b: Int): Int{
return a + b
}
A function’s return type is defined after the :
Functions in Kotlin can be declared at the root of the Kotlin file.
在以下位置定义函数的返回类型:
Kotlin中的函数可以在Kotlin文件的根声明。
== is used to compare the values are equal or not. === is used to check if the references are equal or not.
==用于比较值是否相等。 ===用于检查引用是否相等。
public
is the default visibility modifier.
public
是默认的可见性修饰符。
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.
class A{
}
class B : A(){
}
不行 默认情况下,类在Kotlin中是final。 要使它们成为非最终值,您需要添加open
修饰符。
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
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.
init
是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
.
默认情况下,除非显式设置为var
否则构造函数参数为val
。
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()
不行 与Java不同,在Kotlin中,new不是关键字。
我们可以通过以下方式实例化一个类:
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
的switch
。
when中的默认语句使用else语句表示。
when
语句中有默认的break语句时。
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) {
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.
在Java中,要创建一个存储数据的类,您需要设置变量,getter和setter,并覆盖toString()
, hash()
和copy()
函数。
在Kotlin中,您只需要在类上添加data
关键字,以上所有内容就会在后台自动创建。
data class Book(var name: String, var authorName: String)
fun main(args: Array) {
val book = Book("Kotlin Tutorials","Anupam")
}
因此,数据类为我们节省了很多代码。
它为每个变量创建组件函数,例如component1()
.. componentN()
。
Destructuring Declarations is a smart way to assign multiple values to variables from data stored in objects/arrays.
Within paratheses, we’ve set the variable declarations. Under the hood, destructuring declarations create component functions for each of the class variables.
解构声明是将对象/数组中存储的数据的多个值分配给变量的一种聪明方法。
在括号内,我们设置了变量声明。 在幕后,解构声明为每个类变量创建组件函数。
Inline functions 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.
infix functions on the other are used to call functions without parentheses or brackets. Doing so, the code looks much more like a natural language.
内联函数用于防止调用匿名函数/ lambda表达式的对象分配,从而节省了内存开销。 相反,它在运行时将函数主体提供给调用它的函数。 这会稍微增加字节码的大小,但可以节省大量内存。
另一方面, infix函数用于调用不带括号或括号的函数。 这样做,代码看起来更像是一种自然语言。
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
两者都用于延迟Kotlin中的属性初始化
lateinit
是与var一起使用的修饰符,用于稍后将值设置为var。
lazy
是一种方法,或者说是lambda表达式。 它仅在val上设置。 val将在需要时在运行时创建。
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.
要为我们的类使用单例模式,我们必须使用关键字object
object
不能具有构造函数集。 我们可以在其中使用init块。
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:
To invoke this we simply do: A.a()
.
不行 Kotlin没有static关键字。
要在我们的类中创建静态方法,请使用companion object
。
以下是Java代码:
class A {
public static int returnMe() { return 5; }
}
等效的Kotlin代码如下所示:
要调用它,我们只需做: Aa()
。
val arr = arrayOf(1, 2, 3);
The type is Array
类型是Array
That’s all for Kotlin interview questions and answers.
这就是Kotlin面试问题和答案的全部内容。
翻译自: https://www.journaldev.com/20567/kotlin-interview-questions
kotlin面试