Kotlin 基础(TeamCity Pipeline 用)
Kotlin 基础(TeamCity Pipeline 用)
TeamCity 的 pipeline 配置用 Kotlin DSL 写,所以先把 Kotlin 语言基础过一遍。参考 Kotlin Tour。
IDE 用 IntelliJ IDEA 或 VSCode。本地 TeamCity server 的 DSL 文档一直挂在 <TeamCity_server_URL>/app/dsl-documentation/index.html。
变量
val 只读,var 可变。
val a = 1 // read-only variables
var b = 2 // mutable variables
b=3
println("a = ${a}") // a = 1
类型
| 类别 | 基本类型 |
|---|---|
| 整数 | Byte, Short, Int, Long |
| 无符号整数 | UByte, UShort, UInt, ULong |
| 浮点数 | Float, Double |
| 布尔 | Boolean |
| 字符 | Char |
| 字符串 | String |
声明可以分三种:只声明不初始化、显式标类型并初始化、初始化但不写类型(类型推断)。
fun main() {
// Variable declared without initialization
val d: Int
// Variable initialized
d = 3
// Variable explicitly typed and initialized
val e: String = "hello"
//Variable initialization without type
val c = 3.12
// Variables can be read because they have been initialized
println(d) // 3
println(e) // hello
println(c) // 3.12
}
可空类型
类型后加 ? 表示可空。
fun main() {
var a: String? = null
println(a) // null
// nullable has nullable String type
var nullable: String? = "You can keep a null here"
// This is OK
nullable = null // null
nullable = "test" // test
println(nullable)
}
运算符
复合赋值 +=, -=, *=, /=, %=:
var customers = 10
// Some customers leave the queue
customers = 8
customers = customers + 3 // Example of addition: 11
customers += 7 // Example of addition: 18
customers -= 3 // Example of subtraction: 15
customers *= 2 // Example of multiplication: 30
customers /= 3 // Example of division: 10
println(customers) // 10
集合
List
List 按添加顺序存元素,允许重复。listOf 只读,mutableListOf 可变。
// Read only list
val readOnlyShapes = listOf("triangle", "square", "circle")
println(readOnlyShapes) // [triangle, square, circle]
// Mutable list with explicit type declaration
// Restricting the type of element
var shapes: MutableList<String> = mutableListOf("triangle", "square", "circle")
println(shapes) // [triangle, square, circle]
// Mutable list without type
var shapes1 = mutableListOf("triangle", "square", "circle")
shapes1[1]="1"
println(shapes1) // [triangle, 1, circle]
常用函数:first() 第一个、last() 最后一个、count() 长度、add(item) 添加、remove(item) 删除(删第一个匹配)、filter(fn) 过滤、map(fn) 变换、fold(初始值, fn(x, item)) 从左到右累加。
println(listOf(1, 2, 3).fold(3, { x, item -> x *item })) // 18
用 in 判断元素是否在 list 里:
fun main() {
val readOnlyShapes = listOf("triangle", "square", "circle")
println("circle" in readOnlyShapes)// true
}
Set
Set 无序,只存唯一元素。setOf 只读,mutableSetOf 可变。常用函数 count()、add(item)、remove(item),同样用 in 判断:
fun main() {
val readOnlyFruit = setOf("apple", "banana", "cherry", "cherry")
println("banana" in readOnlyFruit) // true
}
Map
Map 存键值对,用 key 取 value。mapOf 只读,mutableMapOf 可变。
fun main() {
// Read-only map
val readOnlyJuiceMenu = mapOf("apple" to 100, "kiwi" to 190, "orange" to 100)
println(readOnlyJuiceMenu)
// {apple=100, kiwi=190, orange=100}
// Mutable map with explicit type declaration
val juiceMenu: MutableMap<String, Int> = mutableMapOf("apple" to 100, "kiwi" to 190, "orange" to 100)
println(juiceMenu)
// {apple=100, kiwi=190, orange=100}
// Mutable map without type
val juiceMenu1 = mutableMapOf("apple" to "test", "kiwi" to 190, "orange" to 100)
println(juiceMenu1) //{apple=test, kiwi=190, orange=100}
}
常用函数:count() 长度、put(key, value) 添加、remove(key) 删除、containsKey(key) 判断键存在、keys 所有键、values 所有值。in 配合 .keys / .values 用:
fun main() {
val readOnlyJuiceMenu = mapOf("apple" to 100, "kiwi" to 190, "orange" to 100)
println("orange" in readOnlyJuiceMenu.keys)
// true
println(200 in readOnlyJuiceMenu.values)
// false
}
控制流
if
val d: Int
val check = true
if (check) {
d = 1
} else {
d = 2
}
if 是表达式,可以当三元用:
println(if (a > b) a else b) // Returns a value: 2
when
类似 switch:
val obj = "Hello"
when (obj) {
// Checks whether obj equals to "1"
"1" -> println("One")
// Checks whether obj equals to "Hello"
"Hello" -> println("Greeting")
// Default statement
else -> println("Unknown")
}
// Greeting
val temp = 18
val description = when {
// If temp < 0 is true, sets description to "very cold"
temp < 0 -> "very cold"
// If temp < 10 is true, sets description to "a bit cold"
temp < 10 -> "a bit cold"
// If temp < 20 is true, sets description to "warm"
temp < 20 -> "warm"
// Sets description to "hot" if no previous condition is satisfied
else -> "hot"
}
println(description)
循环
for:
for (number in 1..5) {
// number is the iterator and 1..5 is the range
print(number)
}
// 12345
val cakes = listOf("carrot", "cheese", "chocolate")
for (cake in cakes) {
println("Yummy, it's a $cake cake!")
}
while:
var cakesEaten = 0
while (cakesEaten < 3) {
println("Eat a cake")
cakesEaten++
}
do ... while:
var cakesEaten = 0
var cakesBaked = 0
do {
println("Bake a cake")
cakesBaked++
} while (cakesBaked < cakesEaten)
函数
fun sum(x: Int, y: Int): Int {
return x + y
}
Lambda 表达式,形式 { 参数名: 类型 -> 表达式 } 或 { 参数名 -> 表达式 }:
println({ text: String -> text.uppercase() }("hello"))
val upperCaseString: (String) -> String = { text -> text.uppercase() }
fun main() {
println(upperCaseString("hello"))
// HELLO
}
类
class Contact(val id: Int, var email: String) {
fun printId() {
println(id)
}
}
fun main() {
val contact = Contact(1, "mary@gmail.com")
// Calls member function printId()
contact.printId()
// 1
}
data class 自带几个方法:
| 方法 | 作用 |
|---|---|
.toString() | 打印可读的实例字符串(含属性) |
.equals() 或 == | 比较两个实例 |
.copy() | 复制一个实例,可改部分属性 |
val user = User("Alex", 1)
// Automatically uses toString() function so that output is easy to read
println(user.toString()) // User(name=Alex, id=1)
println(user) // User(name=Alex, id=1)
val user = User("Alex", 1)
val secondUser = User("Alex", 1)
val thirdUser = User("Max", 2)
// Compares user to second user
println("user == secondUser: ${user == secondUser}") // user == secondUser: true
// Compares user to third user
println("user == thirdUser: ${user.equals(thirdUser)}") // user == thirdUser: false
val user = User("Alex", 1)
val secondUser = User("Alex", 1)
val thirdUser = User("Max", 2)
// Creates an exact copy of user
println(user.copy())
// User(name=Alex, id=1)
// Creates a copy of user with name: "Max"
println(user.copy("Max"))
// User(name=Max, id=1)
// Creates a copy of user with id: 3
println(user.copy(id = 3))
// User(name=Alex, id=3)