本篇博客主要记录,自己在使用 kotlin 过程中的心得和与 java 语言基本语法的不同点。文章内容会不断更新。
1:
java中的嵌套类:
cass A{
class B{
}
}
kotlin中的嵌套类:
cass A{
inner class B{
}
}
说明:是的,kotlin 要添加 inner 关键字,如果不加 inner 关键字, 默认嵌套类是静态的。
2:
作用域
- public:默认,总是可见
- internal:同模块可见
- private:声明范围与同模块的子作用域可见
- protected:类似于private,但对子类也可见
3:数组
java 的写法:
String[] strArgs1 = new String[10];
String[] strArgs2 = {"22", "33"};
Integer[] intArgs1 = new Integer[10];
Integer[] intArgs2 = {1, 2, 3, 4};
kotlin 的写法:
var strArgs1 = arrayOfNulls<String>(10)
var strArgs2 = arrayOf("22", "33")
var intArgs1 = arrayOfNulls<Int>(10)
var intArgs2 = arrayOf(1, 2, 3, 4)
int 类型也可以这样写:
var intArgs3 = intArrayOf(1, 2, 3, 4)
3:list 判空
val list: MutableList<String> = ArrayList()
if (list.isEmpty()) {
println("MainActivity.onCreate list isEmpty")
}
if (list.isNullOrEmpty()) {
println("MainActivity.onCreate list isNullOrEmpty")
}
if (list.isNotEmpty()) {
println("MainActivity.onCreate list isNotEmpty")
}
if (list != null && list.size > 0) {
println("MainActivity.onCreate list != null && list.size > 0")
}
打印日志如下:
val list: MutableList<String>? = null
if (list?.isEmpty() == true) {
println("MainActivity.onCreate list isEmpty")
}
if (list.isNullOrEmpty()) {
println("MainActivity.onCreate list isNullOrEmpty")
}
if (list?.isNotEmpty() == true) {
println("MainActivity.onCreate list isNotEmpty")
}
if (list != null && list.size > 0) {
println("MainActivity.onCreate list != null && list.size > 0")
}
日志如下:
var list: MutableList<String> = ArrayList()
list.add("123")
if (list.isEmpty()) {
println("MainActivity.onCreate list isEmpty")
}
if (!list.isNullOrEmpty()) {
println("MainActivity.onCreate list isNullOrEmpty")
}
if (list.isNotEmpty()) {
println("MainActivity.onCreate list isNotEmpty")
}
if (list != null && list.size > 0) {
println("MainActivity.onCreate list != null && list.size > 0")
}
总结:推荐用第一种判断。
- if (list != null && list.size > 0) 和 if (!list.isNullOrEmpty()) 是等效判断
- if (list.isNotEmpty()) 和 if (list.size > 0) 是等效判断
进一步说明下:NetUtils.getList()是java方法返回的空list。
public static ArrayList<String> getList() {
return null;
}
var list = NetUtils.getList()
if (!list.isNullOrEmpty()) {
println("MainActivity.onCreate list isNullOrEmpty not")
} else {
println("MainActivity.onCreate list isNullOrEmpty")
}
if (list != null && list.size > 0) {
println("MainActivity.onCreate list != null && list.size > 0")
} else {
println("MainActivity.onCreate else")
}
if (list.isNotEmpty()) {
println("MainActivity.onCreate list isNullOrEmpty")
}
打印日志如下:
总结:直接进行 if (list.isNotEmpty()) 判断 和 if (list.size > 0) 一样,如果list为空,会报空指针!