目录
这一节主要介绍Kotlin基础部分,与Java有区别的地方。介绍一些基础,控制流和异常内容。
1. 基础
val和var
var指向可变引用
val指向一个不可变的引用,但是如果这个引用是可变的
val languages = array("Java","C++");
//languages = array("Java","C++") //错误
languages.add("kotlin") //正确
支持数字字面加下划线
val oneMillion = 1_000_000
val creditCardNumber = 1234_5678_9012_3456L
val socialSecurityNumber = 999_99_9999L
自动装箱
val a: Int = 10000 //a是基础类型
val b: Int? = 10000//b是装箱猴的包装类型
注意比较
注意比较(equals(),==\,=\==)kotlin的==类似但是不等于equal(),等于a?.equal(b)?:b==null,这样就不用考虑空指针的问题,但是与equals()比较类似,就不用equals()单独拿出来对比。
==可以理解为数值上的相等,===理解地址的相等
// 基础类型与基础类型的对比
val a : Int = 10000
val b : Int = 10000
println(a == b)
println(a === b)
// 基础类型与包装类型的对比
val a : Int = 10000
val b : Int?= 10000
println(a == b)
println(a === b)
// 包装与包装类型的对比
val a : Int? = 10000
val b : Int? = 10000
println(a == b)
println(a === b)
// true true true false true false
// 将一个基础类型装箱不能保证同一性但不能保证相等性
val a : Int = 10000
val b : Int? = a
val c : Int? = a
println(b == c)
println(b === c)
// true false
// kotlin跟java一样会缓存-128-127之间的int包装类型
val a : Int = 127
val b : Int? = a
val c : Int? = a
println(b == c)
println(b === c)
// true true
类型转换
Java的基础类型是可以由小类型转大类型的,而Kotlin不行,更别说包装类型了
val b: Byte = 1 // OK
val i: Int = b // 错误
val b: Byte? = 1 // OK
val i: Int? = b // 错误
// 如果需要显示转换,要拓宽数据
val i: Int = b.toInt() // 显式拓宽
print(i)
位运算
不支持直接使用位运算,需要调用对应函数
shl(bits) – 有符号左移 (Java 的 <<)
shr(bits) – 有符号右移 (Java 的 >>)
ushr(bits) – 无符号右移 (Java 的 >>>)
and(bits) – 位与
or(bits) – 位或
xor(bits) – 位异或
inv() – 位非
数组
可以理解Kotlin把数组整合成了一个类Array,这个类具有size属性、get、set方法,它的创建函数是:
arrayOf(1,2,3) // 直接传递元素
arrayOfNulls() //元素为空的数组
// 创建一个 Array<String> 初始化为 ["0", "1", "4", "9", "16"],中括号的参数是索引
val asc = Array(5) { i -> (i * i).toString() }
for (item in collection) { print(item) }
遍历查看下面的for循环
map
val airports= mapOf<String ,String>(Pair("PVG","浦东"),Pair("SHA","虹桥"),Pair("HGH","萧山"))
println(airports.size)
println(airports["PVG"])
for((add,where) in airports){
println("$add = $where")
}
2 .控制流
if
if not null 写成 printf(files?.size)
if not null and else 写成 println(files?.size?:"empty")
if null 写法 val email = values["email"] ?: throw IllegalStateException("Email is miss")
for
//遍历元素
for (item in collection) { print(item) }
//遍历索引,(更加智能的方案)
for (index in 0..viewGroup.getChildCount() - 1) { val view = viewGroup.getChildAt(index) view.visibility = View.VISIBLE }
//在我们迭代一个a数组或集合,indices直接获得索引范围
for (i in array.indices) print(array[i])
when
when表达式与Java中的switch/case类似,但是要强大得多。
这个表达式会去 试图匹配所有可能的分支直到找到满意的一项,然后它会运行右边的表达式,可以增加else分支匹配无分支匹配的情况。
3. 异常
Kotlin不区分受检异常和非受检异常,通常在catch中返回值而不是抛出错误。try/catch可以作为一个表达式。
//java
public class TryCatchAndFinally {
public static void main(String[] args){
BufferedReader bufferedReader = new BufferedReader(new StringReader("234"));
try {
System.out.println(readNumber(bufferedReader));
} catch (IOException e) {
e.printStackTrace();
}
}
public static int readNumber(BufferedReader reader) throws IOException {
try {
String readLine = reader.readLine();
return Integer.parseInt(readLine);
} catch (NumberFormatException e) {
return -1; //不是数字,返回-1
}finally {
reader.close();
}
}
}
//kotlin
fun readNumber(reader: BufferedReader){
val number = try {
Integer.parseInt(reader.readLine())
}catch (e: NumberFormatException){
null
}
println(number)
}
fun main(args: Array<String>) {
val bufferedReader = BufferedReader(StringReader("not a number"))
readNumber(bufferedReader)
}