Kotlin 基本语法官方文档:
https://kotlinlang.org/docs/basic-syntax.html
以下是罗列的详细点
1. source files can be placed arbitrarily in the file
package my.demo
import kotlin.text.*
2. an entry point of a Kotlin application is the main function
fun main(args: Array) {
println(args.contentToString())
}
3. Print
and Println
fun main() {
print("Hello ")
print("world!")
}
print:
Hello world!
fun main() {
println("Hello world!")
println(42)
}
print:
Hello world!
42
4.Function --- using fun
keyword
Unit
return Type can be omitted(可以不写返回值)
fun printSum(a: Int, b: Int): Unit {
println("sum of $a and $b is ${a + b}")
}
or
fun printSum(a: Int, b: Int){
println("sum of $a and $b is ${a + b}")
}
using default arguments can reduces a number of overloads compared to other languages
fun read(
b: ByteArray,
off: Int = 0,
len: Int = b.size,
) { /*...*/ }
5. val
& var
val
: read-only local variables are defined using the keyword
var
: can be reassigned
6. class
Inheritance between classes is declared by a colon (: ). Classes are final by default; to make a class inheritable, mark it as open.
open class Shape
class Rectangle(var height: Double, var length: Double): Shape() {
var perimeter = (height + length) * 2
}
7. comments
/**
* A group of *members*.
*
* This class has no useful logic; it's just a documentation example.
*
* @param T the type of a member in this group.
* @property name the name of this group.
* @constructor Creates an empty group.
*/
class Group(val name: String) {
/**
* Adds a [member] to this group.
* @return the new size of the group.
*/
fun add(member: T): Int { ... }
}
往后需要编写api文档的可以参考:
https://kotlinlang.org/docs/kotlin-doc.html#block-tags
8.String templates
using $[变量]
or ${ [变量.子变量] }
val s2 = "${s1.replace("is", "was")}, but now is $a"
9. Conditional expresssion
if
官方文档 : https://kotlinlang.org/docs/control-flow.html#if-expression
if 在简单函数中的运用
fun maxOf(a: Int, b: Int): Int {
if (a > b) {
return a
} else {
return b
}
}
or 简写成
fun maxOf(a: Int, b: Int) = if (a > b) a else b
没有三目运算,所以 if
是很重要的角色
可以替代三目运算写成
val max = if (a > b) a else b
也可以使用if
在进行复杂运算之后为变量赋值 ( else
branch is mandatory )
val max = if (a > b) {
/** 稍微复杂运算 */
a /** 返回值 没有 return关键字*/
} else {
print("Choose b")
c
}
10 for
loop
使用value
for ( `[value]` in`[数组]`) {
println(value)
}
or 使用index
for (index in items.indices) {
println("item at $index is ${items[index]}")
}
or 使用 index&value
for ((index, value) in array.withIndex()) {
println("the element at $index is $value")
}
11. while
and do-while
var a = 10
do {
a --
print(a)
}while (a > 5)
print:
9876
12 nothing
type
val s = person.name ?: return
13. 打破并继续标签
Kotlin 中的任何表达式都可以用label 标记。标签具有标识符后跟@符号的形式,例如:abc@, fooBar@。要标记一个表达式,只需在它前面添加一个标签。
为for
循环贴上标签
loop@ for (i in 1..10) {
// ……
}
用标签限制break
loop@ for (i in 1..10) {
for (j in 1..10) {
if (……) break@loop
}
}
被标签限制的break 跳转到指定标签的执行点,也就是一次break 跳出两重循环
用标签限制continue
如果将上述代码中的break 换成continue 那结果就是直接进行第一重循环的下一次迭代
14. return
当前函数中 后续代码不执行
15.When
类似于 switch
fun describe(obj: Any): String =
when (obj) {
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long"
!is String -> "Not a string"
else -> "Unknown"
}
fun main() {
println(describe(1))
println(describe("Hello"))
println(describe(1000L))
println(describe(2))
println(describe("other"))
}
print:
One
Greeting
Long
Not a string
Unknown