基础main函数

1
2
3
fun main() {
println("Hello world!")
}

print,println输出到屏幕上。

函数

默认不填即为Unit。
when类似于switch,if else 只要有结果判定成功,便不再往下判断。
Unit标识无返回类型=>void
前变量名,后数据类型
使用${}作为占位符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//sampleStart
fun sum(a: Int, b: Int): Int {
return a + b
}
//sampleEnd
fun sum(a: Int, b: Int) = a + b

fun main() {
println("sum of 19 and 23 is ${sum(19, 23)}")
printSum(-11,53)
}
fun printSum(a: Int, b: Int): Unit {
println("sum of $a and $b is ${a + b}")
}

变量

如果有赋值,那么它可以自动推出变量类型,否则需要声明变量类型
val 只读变量,不可以修改
var 可读可改变量
const val 常量,必须定义在函数之外。

1
2
3
4
val a: Int = 1  // 立即赋值
val b = 2 // 自动推断出 `Int` 类型
val c: Int // 如果没有初始值类型不能省略
c = 3 // 明确赋值

类与实例

类的属性可以在声明或者主体中列出
要继承一个类,需要使用:,类一遍情况下都默认为final类型,所以要声明为open

1
2
3
4
5
6
7
8
open class Shape
class Rectangle(var height:Double,var length:Double) : Shape(){
var perimeter = (height+length) * 2
}
fun main() {
var rectangle = Rectangle(10.1,20.0)//必须使用.0不然直接运行不了
println(rectangle.perimeter)
}

单行多行注释

1
2
3
4
// 这是一个行注释

/* 这是一个多行的
块注释。 */

字符串模板

用${a}来把变量a合并到字符串中。也可以简写为$a。
它可以使用模板es6的语法如下所示

1
2
3
val price = """
${'$'}_9.99
"""

条件表达式

if else (特殊:他本身也可以作为表达式来使用)

1
var m =  if (a > b) a else b  <=>  m = a>b ? a :b 三元表达式

for循环

1
2
3
4
5
6
7
8
9
10
11
12
13
sampleStart
var items = listOf("apple","banana","xigua")
for (item in items){
println(item)
}

//sampleEnd
//indices表示index
//indeces 表示的是一个集合类型,包括从(0...list.size-1)
//${items[index]} = ${items[item]}
for (index in items.indices) {
println("item at $index is ${items[index]}")
}

while循环

1
2
3
4
5
var index = 0
while (index < items.size){
println("item in $index is ${items[index]}")
index++
}

when表达式<=>switch case但是他的可操作性更强,没有了固定的约束

1
2
3
4
5
6
7
8
fun decsribe(obj:Any):String = when(obj) {
1 -> "One"
2 -> "Two"
"Hello" -> "Greeting"
is Long -> "Long"
!is String -> "Not a string"
else -> "Unknown"
}

使用区间(range)

它满足前闭后闭

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//使用 in 操作符来检测某个数字是否在指定区间内
val x = 10
val 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")
}

//in也可用在for,while循环中区间迭代
for (x in 1..5) {
print(x)
}
//或者数列迭代,并控制步进大小
for(x in 1..5 step 2){
println(x)
}
for(x in 10 downTo -3 step 3){
println(x)
}

集合

使用 in 操作符来判断集合内是否包含某实例。

1
2
3
4
5
6
7
8
9
fun main() {
val items = setOf("apple", "banana", "kiwifruit")
//sampleStart
when {
"orange" in items -> println("juicy")
"apple" in items -> println("apple is fine too")
}
//sampleEnd
}

使用 lambda 表达式来过滤(filter)与映射(map)集合:

1
2
3
4
5
6
7
8
9
10
fun main() {
//sampleStart
val fruits = listOf("banana", "avocado", "apple", "kiwifruit")
fruits
.filter { it.startsWith("a") }
.sortedBy { it }
.map { it.uppercase() }
.forEach { println(it) }
//sampleEnd
}

空值和空检测

当可能用 null 值时,必须将引用显式标记为可空。可空类型名称以问号(?)结尾。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
fun parseInt(str: String): Int? {
return str.toIntOrNull()
}

//sampleStart
fun printProduct(arg1: String, arg2: String) {
val x = parseInt(arg1)
val y = parseInt(arg2)

// 直接使用 `x * y` 会导致编译错误,因为它们可能为 null
if (x != null && y != null) {
// 在空检测后,x 与 y 会自动转换为非空值(non-nullable)
println(x * y)
}
else {
println("'$arg1' or '$arg2' is not a number")
}
}
//sampleEnd

fun main() {
printProduct("6", "7")
printProduct("a", "7")
printProduct("a", "b")
}

类型检测和自动类型转化

is 操作符检测一个表达式是否某类型的一个实例,当某个变量进行判断后,他会自动转换为这个类型,并作为该类型使用
即便是在判断的右侧他也会自动转化为对应的判断类型。
如下:

1
2
3
4
5
6
fun getStringLength(obj: Any): Int? {
// 在 `&&` 运算符的右侧, `obj` 的类型会被自动转换为 `String`
if (obj is String && obj.length > 0)
return obj.length
return null
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//sampleStart
fun getStringLength(obj: Any): Int? {
if (obj is String) {
// `obj` 在该条件分支内自动转换成 `String`
return obj.length
}

// 在离开类型检测分支后,`obj` 仍然是 `Any` 类型
return null
}
//sampleEnd

fun main() {
fun printLength(obj: Any) {
println("Getting the length of '$obj'. Result: ${getStringLength(obj) ?: "Error: The object is not a string"} ")
}
printLength("Incomprehensibilities")
printLength(1000)
printLength(listOf(Any()))
}