基于官网的 Getting Start 的基础语法部分一,一共三节,这篇是第一节,翻译如下:
基础语法
定义一个包
包的声明必须放在文件头部:
- package my.demo
- import java.util.*
- // ...
不需要加上 package 的路径,kotlin 可以自动定位 package 的位置。
查看更多 packages
定义函数
参数是两个 int 型,并且返回值也是 int 型的函数:
- fun sum(a: Int, b: Int): Int {
- return a + b
- }
没有指定返回值的函数表达式,编辑器会自动推断返回类型:
- fun sum(a: Int, b: Int) = a + b
无返回值的函数(Unit,相当于 java 的 Void):
- 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}")
- }
查看 Functions
定义变量
定义不可变变量:
- val a: Int = 1 // 指定类型的变量
- val b = 2 // 推断为`Int`型
- val c: Int // 没有初始值时必须指定变量类型
- c = 3 // 赋值
定义可变变量:
- var x = 5 // 推断为`Int`型
- x += 1
查看更多 Properties And Fields
注释
同 java 与 javascript,支持单行与块注释:
- // This is an end-of-line comment
- /* This is a block comment
- on multiple lines. */
不同于 java 的是,kotlin 的区块注释是可以嵌套的。
查看更多 Documenting Kotlin Code
字符串模板
- var a = 1
- // 字符变量:
- val s1 = "a is $a"
- a = 2
- // 任意表达式:
- val s2 = "${s1.replace("is", "was")}, but now is $a"
查看更多 String templates
If 语句
- fun maxOf(a: Int, b: Int): Int {
- if (a > b) {
- return a
- } else {
- return b
- }
- }
if 的表达式写法:
- fun maxOf(a: Int, b: Int) =
- if (a > b) a
- else b
查看更多 if-expressions
Null 的用法
引用的参数可能为 null 时,应该标记为 null。
例:str 不能被转换为 Int 型时会返回 null:
- fun parseInt(str: String): Int {
- // ...
- }
函数中使用 null:
- fun printProduct(arg1: String, arg2: String) {
- val x =parseInt(arg1)
- val y =parseInt(arg2)
- // Using `x * y` yields error because they may hold nulls.
- if (x != null && y != null) {
- // x and y are automatically cast to non-nullable after null check
- println(x *y)
- }
- else{
- println("either '$arg1' or '$arg2' is not a number")
- }
- }
或
- // ...
- if (x == null) {
- println("Wrong number format in arg1: '${arg1}'")
- return}
- if (y == null) {
- println("Wrong number format in arg2: '${arg2}'")
- return
- }
- // x and y are automatically cast to non-nullable after null check
- println(x * y)
查看更多 Null-safety
for 循环
- val items = listOf("apple", "banana", "kiwi")
- for (item in items) {
- println(item)
- }
or
- val items = listOf("apple", "banana", "kiwi")
- for(index in items.indices) {
- println("item at $index is ${items[index]}")
- }
查看更多 for loop
while
- val items = listOf("apple", "banana", "kiwi")
- var index = 0
- while (index <items.size) {
- println("item at $index is ${items[index]}")
- index++
- }
查看更多 See while loop
when 语句
- fun describe(obj: Any): String =when (obj) {
- 1 -> "One"
- "Hello" -> "Greeting"is Long -> "Long"
- !is String -> "Not a string"
- else -> "Unknown"
- }
查看更多 when expression
Range
判断数字是否在范围内:
- val x = 10val y = 9
- if (x in 1..y+1) {
- println("fits in range")
- }
判断数字是否超出范围:
- val list = listOf("a", "b", "c")
- if (-1 !in 0..list.lastIndex) {
- println("-1 is out of range")
- }
- if (list.size !in list.indices) {
- println("list size is out of valid list indices range too")
- }
范围遍历:
- for (x in 1..5) {
- print(x)
- }
过程遍历:
- for(x in 1..10 step 2) {
- print(x)
- }
- for(x in 9 downTo 0 step 3) {
- print(x)
- }
查看更多 Ranges
使用 Collections
遍历 collections:
- for (item in items) {
- println(item)
- }
使用 in 关键字判断集合(collection)里是否包含某个对象(object):
- when {
- "orange" in items -> println("juicy")
- "apple" in items -> println("apple is fine too")
- }
使用 lambda 表达式来过滤(filter)或映射(map)集合(collections):
- fruits.filter {
- it.startsWith("a")
- }.sortedBy {
- it
- }.map {
- it.toUpperCase()
- }.forEach {
- println(it)
- }
来源: http://www.cnblogs.com/joejs/p/6875128.html