Kotlin Quick Start 快速入门
Kotlin Basics 编程基础
Hello world
fun main() {
println("Hello, world!")
// Hello, world!
}
Variables 变量
- Read-only variables with
val只读变量 - Mutable variables with
var可变变量
fun main() {
val popcorn = 5 // 有5盒爆 米花
val hotdog = 7 // 有7个热狗
var customers = 10 // 有10位顾客在排队
// 部分顾客离开队列
customers = 8
println(customers)
// 8
}
String templates 字符串模板
fun main() {
val customers = 10
println("There are $customers customers")
// There are 10 customers
println("There are ${customers + 1} customers")
// There are 11 customers
}
Basic types 基本类型
https://blog.namichong.com/translation-docs/kotlin-docs/kotlin-tour-basic-types.html
Kotlin 能够推断出 customers 变量的类型,即 Int。 Kotlin 的这种推断类型的能力被称为 类型推断 type inference
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
只要在第一次读取之前进行初始化,Kotlin 就可以管理这些变量。
要在不初始化的情况下声明变量,需要使用 : 指定其类型。
// 未初始化的变量声明
val d: Int
// 变量初始化
d = 3
// 显式指定类型并初始化的变量
val e: String = "hello"
// 变量已经初始化,因此可以读取
println(d) // 输出 3
println(e) // 输出 hello
如果在读取变量之前没有初始化它,将会出现错误:
// 未初始化的变量声明
val d: Int
// 触发错误
println(d)
// 报错:Variable 'd' must be initialized
Collections 集合
List 列表
// 只读列表
val readOnlyShapes = listOf("triangle", "square", "circle")
println(readOnlyShapes)
// [triangle, square, circle]
// 带有显式类型声明的可变列表
val shapes: MutableList<String> = mutableListOf("triangle", "square", "circle")
println(shapes)
// [triangle, square, circle]
val readOnlyShapes = listOf("triangle", "square", "circle")
println("列表中的第一个元素是: ${readOnlyShapes[0]}")
// 列表中的第一个元素是: triangle
val readOnlyShapes = listOf("triangle", "square", "circle")
println("列表中的第一个元素是: ${readOnlyShapes.first()}")
// 列表中的第一个元素是: triangle
val readOnlyShapes = listOf("triangle", "square", "circle")
println("该列表有 ${readOnlyShapes.count()} 项")
// 该列表有 3 项
val shapes: MutableList<String> = mutableListOf("triangle", "square", "circle")
// 将 "pentagon" 添加到列表中
shapes.add("pentagon")
println(shapes)
// [triangle, square, circle, pentagon]
// 从列表中移除第一个 "pentagon"
shapes.remove("pentagon")
println(shapes)
// [triangle, square, circle]