0%

Kotlin入门

关键词语

var val

fun

a:Int

open override

constructor

Basic Syntax

Defining packages

1
2
3
4
package my.demo

import java.util.*
// as java

Defining functions

1
2
3
fun sum(a: Int, b: Int): Int {
return a + b
}
1
2
fun sum(a: Int, b: Int) = a + b
// inferred return type
1
2
3
4
5
6
7
8
9
fun printSum(a: Int, b: Int): Unit {
println("sum of $a and $b is ${a + b}")
}
// return no meaningful value

fun printSum(a: Int, b: Int) {
println("sum of $a and $b is ${a + b}")
}
// Unit can be omitted

Defining variables

1
2
3
4
5
6
val a: Int = 1
val b = 2 // type can be inferred

val c: Int
c = 3
// read-only local variables are defined using val
1
2
3
var x = 5 // Int type is inferred
x += 1
// variables can be reassigned use var

Comments

1
2
3
4
5
6
7
8
9
10
// 

/*
*/

/*
/*
*/
*/
// block comments can be nested

Using string templates

1
2
3
4
5
6
var a = 1
val s1 = "a is $a"

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

Using conditional expressions

1
2
3
4
5
6
7
fun maxOf(a: Int, b: Int): Int {
if (a > b) {
return a
} else {
return b
}
}
1
fun maxOf(a: Int, b: Int) = if (a > b) a else b

Using nullable values and checking for null

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
fun parseInt(str: String): Int? { 
// return null if str is not a integer
return str.toIntOrNull()
}
// Int?

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

//! x * y
// Error: x y might be null

if (x != null && y != null) {
// x y automatically cast to non-nullable after null check
println(x * y);
}
else {
println("either '$arg1' or '$arg2 is not a number" )
}
}
1
2
3
4
5
6
7
fun printProduct(arg1: String, arg2: String) {
// ...
if (x != null && y != null) {
// x y automatically cast to non-nullable after null check
println(x * y);
}
// ...

Using type checks and automatic casts

1
2
3
4
5
6
7
fun getStringLength(obj: Any): Int? {
if (obj is String) {
return obj.length
}

return null
}
1
2
3
4
5
6
fun getStringLength(obj: Any): Int? {
if (obj !is String) return null

// `obj` 在这一分支自动转换为 `String`
return obj.length
}
1
2
3
4
5
6
7
8
fun getStringLength(obj: Any): Int? {
// `obj` 在 `&&` 右边自动转换成 `String` 类型
if (obj is String && obj.length > 0) {
return obj.length
}

return null
}

Using a for loop

1
2
3
4
var items = listOf("apple", "banana", "kiwifruit")
for (item in items) {
println(item)
}
1
2
3
4
var items = listOf("apple", "banana", "kiwifruit")
for (index in items.indices) {
println(items[index])
}

Using a while loop

1
2
3
4
5
6
var items = listOf("apple", "banana", "kiwifruit")
var index = 0
while (index < items.size) {
println(items[index])
index++
}

Using when expression

1
2
3
4
5
6
7
8
9
10
fun describe(obj: Any): String =
when(obj) {
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long"
!is String -> "Not a string"
in 1..10 -> print("obj is in the range")
// else is required
else -> "Unknown"
}

Using ranges

1
2
3
4
5
val x = 10
val y = 9
if (x in 1..y+1) {
println("fits in range")
}
1
2
3
4
5
6
7
8
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")
}
1
2
3
for (x in 1..5) {
print(x)
}
1
2
3
4
5
6
7
8
for (x in 1..10 step 2) {
print(x)
}
println()
for (x in 9 downTo 0 step 3) {
print(x)
}
// step

Using collections

1
2
3
4
when {
"orange" in items -> println("juicy")
"apple" in items -> println("apple is fine too")
}

Creating basic classes and their instances

1
2
3
var rectangle = Rectangle(5.0, 2.0)
var triangle = Triangle(3.0, 4.0, 5.0)
// new is not required

数据类

1
2
3
data class Student (
var name : String,
var id : Int)

一个关键字实现单例

1
2
3
4
5
6
7
8
9
object Log {
fun i(string: String) {
println(string)
}
}

fun main(args: Array<String>) {
Log.i("test")
}

use

1
inline fun <T : Closeable?, R> T.use(block: (T) -> R): R

Executes the given block function on this resource and then closes it down correctly whether an exception is thrown or not.

用于实现了Closeable接口的类,执行闭包函数,然后关闭类,不管有没有异常。

2020-3-6 23:12:57