基本语法

定义包名

在源文件的开头定义包名:

package my.demo
import java.util.*

包名不必和文件夹路径一致:源文件可以放在任意位置。

更多请参看 包(package)

定义函数

定义一个函数接受两个 int 型参数,返回值为 int :

funsum(a: Int , b: Int) : Int{return a + b
}

funmain(args: Array) {
  print("sum of 3 and 5 is ")
  println(sum(3, 5))
}

该函数只有一个表达式函数体以及一个自推导型的返回值:

funsum(a: Int, b: Int) = a + bfunmain(args: Array) {
  println("sum of 19 and 23 is ${sum(19, 23)}")
}

返回一个没有意义的值:

funprintSum(a: Int, b: Int): Unit {
  println("sum of $a and $b is ${a + b}")
}

funmain(args: Array) {
  printSum(-1, 8)
}

Unit 的返回类型可以省略:

funprintSum(a: Int, b: Int) {
  println("sum of $a and $b is ${a + b}")
}

funmain(args: Array) {
  printSum(-1, 8)
}

更多请参看函数

定义局部变量

声明常量:

funmain(args: Array) {val a: Int = 1val b = 2val c: Int
  c = 3
  println("a = $a, b = $b, c = $c")
}

变量:

funmain(args: Array) {var x = 5
  x += 1
  println("x = $x")
}

更多请参看属性和字段

注释

与 java 和 javaScript 一样,Kotlin 支持单行注释和块注释。


 

与 java 不同的是 Kotlin 的 块注释可以级联。

参看文档化 Kotlin 代码学习更多关于文档化注释的语法。

使用字符串模板

funmain(args: Array) {var a = 1val s1 = "a is $a"

  a = 2val s2 = "${s1.replace("is", "was")}, but now is $a"
  println(s2)
}

更多请参看字符串模板

使用条件表达式

funmaxOf(a: Int, b: Int): Int {if (a > b) {
        return a
    } else {
        return b
    }
}

funmain(args: Array) {
    println("max of 0 and 42 is ${maxOf(0, 42)}")
}

把if当表达式:

funmaxOf(a: Int, b: Int) = if(a > b) a else bfunmain(args: Array) {
    println("max of 0 and 42 is ${maxOf(0, 42)}")
}

更多请参看if表达式

使用可空变量以及空值检查

当空值可能出现时应该明确指出该引用可空。

下面的函数是当 str 中不包含整数时返回空:

funparseInt(str : String): Int?{
}

使用一个返回可空值的函数:

funparseInt(str: String): Int? {return str.toIntOrNull()
}

funprintProduct(arg1: String, arg2: String) {val x = parseInt(arg1)
  val y = parseInt(arg2)

  if (x != null && y != null) {
    
    println(x * y)
  }
  else {
    println("either '$arg1' or '$arg2' is not a number")
  }    
}


funmain(args: Array) {
  printProduct("6", "7")
  printProduct("a", "7")
  printProduct("a", "b")
}

或者这样

funparseInt(str: String): Int? {return str.toIntOrNull()
}

funprintProduct(arg1: String, arg2: String) {val x = parseInt(arg1)
  val y = parseInt(arg2)

  if (x == null) {
    println("Wrong number format in arg1: '${arg1}'")
    return
  }
  if (y == null) {
    println("Wrong number format in arg2: '${arg2}'")
    return
  }

  
  println(x * y)
}

更多请参看空安全

使用值检查并自动转换

使用 is 操作符检查一个表达式是否是某个类型的实例。如果对不可变的局部变量或属性进行过了类型检查,就没有必要明确转换:

fungetStringLength(obj: Any): Int? {if (obj is String) {
    return obj.length
  }

  returnnull
}


funmain(args: Array) {funprintLength(obj: Any) {
    println("'$obj' string length is ${getStringLength(obj) ?: "... err, not a string"} ")
  }
  printLength("Incomprehensibilities")
  printLength(1000)
  printLength(listOf(Any()))
}

或者这样

fungetStringLength(obj: Any): Int? {if (obj !is String) returnnullreturn obj.length
}


funmain(args: Array) {funprintLength(obj: Any) {
    println("'$obj' string length is ${getStringLength(obj) ?: "... err, not a string"} ")
  }
  printLength("Incomprehensibilities")
  printLength(1000)
  printLength(listOf(Any()))
}

甚至可以这样

fungetStringLength(obj: Any): Int? {if (obj is String && obj.length > 0) {
    return obj.length
  }

  returnnull
}


funmain(args: Array) {funprintLength(obj: Any) {
    println("'$obj' string length is ${getStringLength(obj) ?: "... err, is empty or not a string at all"} ")
  }
  printLength("Incomprehensibilities")
  printLength("")
  printLength(1000)
}

更多请参看 类型转换

使用循环

funmain(args: Array) {val items = listOf("apple", "banana", "kiwi")
  for (item in items) {
    println(item)
  }
}

或者

funmain(args: Array) {val items = listOf("apple", "banana", "kiwi")
  for (index in items.indices) {
    println("item at $index is ${items[index]}")
  }
}

参看for循环

使用 while 循环

funmain(args: Array) {val items = listOf("apple", "banana", "kiwi")
  var index = 0while (index < items.size) {
    println("item at $index is ${items[index]}")
    index++
  }
}

参看while循环

使用 when 表达式

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

funmain(args: Array) {
  println(describe(1))
  println(describe("Hello"))
  println(describe(1000L))
  println(describe(2))
  println(describe("other"))
}

参看when表达式

使用ranges

检查 in 操作符检查数值是否在某个范围内:

funmain(args: Array) {val x = 10val y = 9if (x in1..y+1) {
      println("fits in range")
  }
}

检查数值是否在范围外:

funmain(args: Array) {val list = listOf("a", "b", "c")

  if (-1 !in0..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")
  }
}

在范围内迭代:

funmain(args: Array) {for (x in1..5) {
    print(x)
  }
}

或者使用步进:

funmain(args: Array) {for (x in1..10 step 2) {
    print(x)
  }
  for (x in9 downTo 0 step 3) {
    print(x)
  }
}

参看Ranges

使用集合

对一个集合进行迭代:

funmain(args: Array) {val items = listOf("apple", "banana", "kiwi")
  for (item in items) {
    println(item)
  }
}

使用 in 操作符检查集合中是否包含某个对象

funmain(args: Array) {val items = setOf("apple", "banana", "kiwi")
  when {
    "orange"in items -> println("juicy")
    "apple"in items -> println("apple is fine too")
  }
}

使用lambda表达式过滤和映射集合:

funmain(args: Array) {val fruits = listOf("banana", "avocado", "apple", "kiwi")
  fruits
    .filter { it.startsWith("a") }
    .sortedBy { it }
    .map { it.toUpperCase() }
    .forEach { println(it) }
}

参看高阶函数和lambda表达式


本文转载自:https://huanglizhuo.gitbooks.io/kotlin-in-chinese/content/GettingStarted/Basic-Syntax.html