您的位置:首页 > 其它

Kotlin基本语法

2017-05-19 11:02 232 查看
2017年Google I/O大会,确定从Android Studio 3.0开始,官方支持Kotlin。

kotlin官网上,资料还是比较全的:
http://kotlinlang.org/docs/reference/basic-syntax.html https://kotlinlang.org/docs/tutorials/koans.html
还有在线编辑器:
https://try.kotlinlang.org/#/Kotlin%20Koans/Introduction/Hello,%20world!/Task.kt
下文按照http://kotlinlang.org/docs/reference/basic-syntax.html的顺序,其中和java比较相似的特性就略过了:

与java相同,Kotlin也有package的概念,还需要import

Kotlin定义函数

fun sum(a: Int, b: Int): Int {
return a + b
}可以简化为
fun sum(a: Int, b: Int) = a + b

没有返回值的函数定义使用Unit
fun printSum(a: Int, b: Int): Unit {
println("sum of $a and $b is ${a + b}")
}或者省略Unit
fun printSum(a: Int, b: Int) {
println("sum of $a and $b is ${a + b}")
}


关于变量的定义,Kotlin参考scala使用了var和val
val a: Int = 1 // immediate assignment
val b = 2 // `Int` type is inferred
val c: Int // Type required when no initializer is provided
c = 3 // deferred assignmentval值初始化之后不能再改变,var可以改变

模板字符串(String Template),可以极大的提高效率
val s = "abc"
val str = "$s.length is ${s.length}" // evaluates to "abc.length is 3"

Null值
Kotlin希望避免空指针带来的问题,所以当一个值要为空的时候,需加上问号

var a: String = "abc"
a = null // compilation error以上代码会编译报错,需要这样:
var b: String? = "abc"
b = null // ok同样的,当一个函数需要返回null的时候
fun parseInt(str: String): Int? {
// ...
}
如果没有问号,会编译报错

when表达式

when表达式替代了繁琐的switch-case

fun describe(obj: Any): String =
when (obj) {
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long"
!is String -> "Not a string"
else -> "Unknown"
}

fun main(args: Array<String>) {
println(describe(1))
println(describe("Hello"))
println(describe(1000L))
println(describe(2))
println(describe("other"))
}

范围
使用in来判断一个数是否在某个范围中,用step来改变幅度

for (x in 1..10 step 2) {
print(x)
}
for (x in 9 downTo 0 step 3) {
print(x)
}in也能用于一个集合
fun main(args: Array<String>) {
val items = setOf("apple", "banana", "kiwi")
when {
"orange" in items -> println("juicy")
"apple" in items -> println("apple is fine too")
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Kotlin