- 1 条件表达式(conditional expression)
fun main(args: Array<String>) {
println(max(Integer.parseInt("20"), Integer.parseInt("30"))
}
fun max(a: Int, b: Int) = if (a > b) a else b
30
Integer.parseInt("20")将"20"转成Int的包装类,并赋值给a ,让后比较a b,输出结果
- 2 检查空(null -checks)
fun parseInt(str: String): Int? {
try {
return Integer.parseInt(str)
} catch (e: NumberFormatException) {
println("其中有参数不是Int类型")
}
return null
}
fun main(args: Array<String>) {
if (args.size == 2) { //假 false
println("No number supplied");
} else {
val x = parseInt("2")
val y = parseInt("3")
// We cannot say 'x * y' now because they may hold nulls
if (x != null && y != null) {
print(x * y) // Now we can
} else {
println("有参数为空")
}
}
}
6
其中要注意try catch的执行流程. Int 后的 ? 不要漏了 ,表示判断
- 3 is 关键字的使用
fun main(args: Array<String>) {
println(getStringLength("aaa"))
println(getStringLength(1))
}
fun getStringLength(obj: Any): Int? {
if (obj is String)
return obj.length // no cast to String is needed
return null
}
3
null
obj is String ? Kotlin 牛逼的地方,一看就知道意思
- 4 while 关键字的使用
fun main(args: Array<String>) {
var i = 0
while (i == args.size)
println(++i)
}
1
顺便了解下++i 和 i++ 的区别,看到var是不是联想到H5里的var,目前没看出和H5有啥区别.
- 5 for 关键字的使用
fun main(args: Array<String>) {
for (arg in args)
println(arg)
// or
println()
for (i in args.indices)
println(args[i])
}
- 6 in 的使用
fun main(args: Array<String>) {
val x = Integer.parseInt("2")
val y = 10
if (x in 1..y - 1) //判断x是否在1 和 y-1 之前,其中y-1 是参与了运算的,
println("OK") //并且x的取值范围是包含了头和尾的
//Iterate over a range: 在一定范围内迭代输出 ${a}的使用
for (a in 1..5)
print("${a} ")
//Check if a number is out of range:
println()
val array = arrayListOf<String>() //集合 泛型 添加元素
array.add("aaa")
array.add("bbb")
array.add("ccc")
if (x !in 0..array.size - 1)
println("Out: array has only ${array.size} elements. x = ${x}")
//Check if a collection contains an object:
if ("aaa" in array) // collection.contains(obj) is called
println("Yes: array contains aaa")
if ("ddd" in array) // collection.contains(obj) is called
println("Yes: array contains ddd")
else
println("No: array doesn't contains ddd")
}
OK
1 2 3 4 5
Yes: array contains aaa
No: array doesn't contains ddd
- 7 when
fun main(args: Array<String>) {
cases("Hello")
cases(1)
cases(System.currentTimeMillis())
cases(MyClass())
cases("hello")
}
fun cases(obj: Any) {
when (obj) {
1 -> println("One")
"Hello" -> println("Greeting")
is Long -> println("Long")
!is String -> println("Not a string")
else -> println("Unknown")
}
}
class MyClass() {
}
.★. .★. .★. .★. .★. .★. .★. .★. .★ . . 上一页 下一页..★. .★. .★. .★. .★. .★. .★. .★. .★ . .★. .