1、Kotlin特点
- 简洁,相对于Java语言,大大减少代码数量
- 安全,在编译时期就处理了可能会产生的空指针异常,若产生空指针编译不会通过
1、let、also、apply、run、with之间的区别?
函数名 | 定义 | 参数 | 返回值 | 是否扩展函数 |
---|
let | fun <T, R> T.let(block: (T) -> R): R = block(this) | it | 闭包形式返回 | 是 |
also | fun T.also(block: (T) -> Unit): T { block(this); return this } | it | 返回this | 是 |
apply | fun T.apply(block: T.() -> Unit): T { block(); return this } | this | 返回this | 是 |
run | fun <T, R> T.run(block: T.() -> R): R = block() | this | 闭包形式返回 | 是 |
with | fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block() | this | 闭包形式返回 | 否 |
2、Kotlin 中 List 与 MutableList 的区别?
- List:有序接口,只能读取,不能更改元素;
- MutableList:有序接口,可以读写与更改、删除、增加元素。
3、Kotlin中 Unit 类型的作用以及与Java中 Void 的区别?
- 在java中,必须指定返回类型,即void不能省略,但是在kotlin中,如果返回为unit,可以省略。
- java中void为一个关键字,但是在kotlin中unit是一个类。
4、Kotlin与Java混合开发时需要注意哪些问题?
- Kotlin默认是非null类型,java返回null,kotlin需要添加? 表示可为null。
- kotlin使用!! 时,要确认变量不为null, 不然会直接抛异常。
5、Kotlin的构造方法
// 无权限修饰的时候constructor可以省略
class MyTest(name: String) {
val name: String
init {
this.name = name
}
}
// 有权限修饰的时候constructor不可以省略
class MyTest private constructor(val name: String) {
private val name;
init {
this.name = name
}
}
class MyTest {
private var name;
constructor(){
}
constructor(name: String){
this.name = name;
}
}
6、操作符
shl 相当于Java中的左移运算符 <<
shr 相当于Java中的右移运算符 >>
ushr 无符号右移,高位补0 >>>
and 按位与操作 &
or 按位或操作 |
xor 按位异或操作 ^
inv 按位取反 ~