//简写的条件表达式
fun max2(a: Int, b: Int) = if(a > b) a else b
6、可空类型
fun nullableTest() {
//在变量类型后面加上问号,代表该变量是可空变量
var name: String? = "zhangsan"
name = null //可以将null赋值给name变量
var person: String = "tom"
// person = null //这句代码会报错,不可以将null赋值给一个不可空变量
}
函数返回值为可空的例子如下代码:
/*
函数返回值为Int?,表示返回值可为空
当参数为空或者为""时,则返回null,否则使用Java中的字符串转整型的方法
这里也体现了kotlin代码和Java代码无缝集成
*/
fun parseInt(s: String): Int? {
if(s == null || s == "")
return null;
return (s);
}
7、类型检查和自动类型转换
Kotlin中使用is运算符来检查数据类型和做类型转换,如下代码所示:
/*
当函数参数为字符串类型时,就返回字符串的长度,否则返回空
*/
fun getStringLength(n: Any): Int? {
if(n is String)
return //这里会自动将n转化为字符串类型
return null
}
上面的代码还可以写成:
/*
当函数参数为字符串类型时,就返回字符串的长度,否则返回空
*/
fun getStringLength(n: Any): Int? {
if(n !is String)
return null
return //这里会自动将n转化为字符串类型
}
8、for循环和while循环
//for循环的测试代码
fun testFor() {
var arr = arrayOf(1, 3, 4, 5, 6)
for(i in ) { //通过索引循环
println(arr[i])
}
for(num in arr) { //直接使用数组中的对象循环
println(num)
}
}
//while循环的测试代码
fun testWhile() {
var i = 0;
while(i < 10) {
print(" " + i)
i++
}
}
9、when表达式
when表达式就类似于Java中的switch表达式,如下代码所示:
fun main(args: Array<String>) {
testCase("hello world")
}
fun testCase(obj: Any) {
when(obj) {
is String -> {
print("this is string")
}
is Int -> {
print("this is integer")
}
else -> {
print("unkown value")
}
}
}
10、ranges的使用
(1)使用in操作符检查一个数是否在某个范围内
/*
判断分数是否大于等于90,小于等于100
*/
fun isGood(score: Int) {
if(score in 90..100) //ranges是闭区间
println("very good")
else
println("not so good")
}
(2)检查索引是否越界
/*
检查index是否在数组arr的索引范围内
*/
fun checkIndex(index: Int, arr: Array<Int>) {
if(index in 0..) //返回的是数组的最后一位的下标
println("index in bounds")
else
println("index out of bounds")
}
(3)遍历一个范围
for(i in 1..5) {
println(i)
}
也可以通过in运算符遍历一个集合,如下代码:
//in运算符遍历一个字符串数组
fun testStr(arr: Array<String>) {
for(str in arr)
println(str)
}