Kotlin 全知识点的详细梳理,涵盖语法、类型、函数、面向对象、集合、高级特性等,每个知识点都附有极简示例(若有错误或其他欢迎大家在评论区交流):
一、基础语法
1. 程序入口
// 唯一入口函数,无参数无返回值
fun main() {
println("Hello Kotlin") // 输出:Hello Kotlin
}
2. 变量与常量
| 类型 | 关键字 | 可变性 | 示例 |
|---|---|---|---|
| 常量 | val |
引用不可变 | val pi = 3.14 |
| 变量 | var |
引用可变 | var count = 0; count = 1 |
注意 :val修饰的对象内部属性可修改(仅引用不可变):
val list = mutableListOf(1)
list.add(2) // 合法,对象本身可变
3. 注释
// 单行注释
/*
* 多行注释
*/
/**
* 文档注释(支持生成API文档)
*/
二、数据类型与操作
1. 基本数据类型(与 Java 对应关系)
| Kotlin 类型 | Java 类型 | 范围 / 说明 | 示例 |
|---|---|---|---|
Byte |
byte |
-128~127 | val b: Byte = 10 |
Short |
short |
-32768~32767 | val s: Short = 1000 |
Int |
int |
-2³¹~2³¹-1 | val i = 100 |
Long |
long |
-2⁶³~2⁶³-1(后缀 L) | val l = 100L |
Float |
float |
单精度(后缀 F) | val f = 3.14F |
Double |
double |
双精度(默认浮点类型) | val d = 3.14 |
Boolean |
boolean |
true/false |
val flag = true |
Char |
char |
单个 Unicode 字符(单引号) | val c = 'A' |
2. 类型转换(显式转换,无自动提升)
val i: Int = 100
val l: Long = i.toLong() // 必须显式转换,不能直接赋值
val s: String = i.toString() // 转为字符串
3. 字符串
-
字符串模板 :
$变量或${表达式}val name = "Kotlin" println("Name: $name, Length: ${name.length}") // 输出:Name: Kotlin, Length: 6 -
多行字符串 :三引号包裹,保留格式
val text = """ 第一行 第二行 """.trimIndent() // 去除缩进
三、运算符与表达式
1. 算术运算符
val a = 10; val b = 3
println(a + b) // 13
println(a - b) // 7
println(a * b) // 30
println(a / b) // 3(整数除法)
println(a % b) // 1(取余)
2. 比较运算符
val x = 5; val y = 10
println(x == y) // false(结构相等,对应equals)
println(x === y) // false(引用相等,仅对对象有效)
println(x in 1..10) // true(范围包含)
3. 逻辑运算符
val a = true; val b = false
println(a && b) // false(与)
println(a || b) // true(或)
println(!a) // false(非)
四、控制流
1. 条件语句
-
if 表达式 (有返回值)
val max = if (a > b) a else b // 替代三元运算符 -
when 表达式 (替代 switch)
fun judge(x: Any) = when (x) { 0 -> "零" 1, 3, 5 -> "奇数" in 2..4 -> "2-4之间" is String -> "字符串:$x" else -> "其他" } println(judge("test")) // 输出:字符串:test
2. 循环语句
-
for 循环
// 遍历区间 for (i in 1..5 step 2) print(i) // 135(步长2) // 遍历集合 val list = listOf("a", "b") for ((index, value) in list.withIndex()) { println("索引$index: $value") } -
while/do-while
var i = 0 while (i < 3) { print(i++) // 012 } do { print(i--) // 321 } while (i > 0)
3. 跳转语句
// break:跳出循环
for (i in 1..5) {
if (i == 3) break
print(i) // 12
}
// continue:跳过当前迭代
for (i in 1..5) {
if (i == 3) continue
print(i) // 1245
}
五、数组
1. 数组创建
| 方式 | 说明 | 示例 |
|---|---|---|
arrayOf() |
泛型数组(存储对象) | val arr = arrayOf(1, 2, 3) |
| 基本类型数组 | 如IntArray(无装箱开销) |
val intArr = IntArray(3) { it * 2 } |
arrayOfNulls<T>() |
可空类型数组 | val nullArr = arrayOfNulls<String>(2) |
2. 数组操作
val arr = arrayOf(1, 2, 3)
println(arr.size) // 3(长度)
println(arr[0]) // 1(访问元素)
arr[0] = 10 // 修改元素
六、空安全
1. 可空类型声明
val nonNull: String = "abc" // 非空(默认)
val nullable: String? = null // 可空(加?)
2. 安全操作
| 语法 | 作用 | 示例 |
|---|---|---|
?. |
安全调用,为空则返回 null | nullable?.length |
?: |
Elvis 运算符,为空取默认值 | nullable?.length ?: -1 |
!! |
非空断言,为空抛 NPE(谨慎使用) | nullable!!.length |
as? |
安全转换,失败返回 null | val num = obj as? Int |
3. 空安全函数参数
// 要求参数非空
fun printLength(str: String) {
println(str.length)
}
// 允许参数为空
fun printLengthNullable(str: String?) {
println(str?.length ?: 0)
}
七、函数
1. 函数定义
// 完整语法
fun sum(a: Int, b: Int): Int {
return a + b
}
// 表达式函数(单行简化)
fun multiply(a: Int, b: Int) = a * b
2. 函数参数
-
默认参数 :减少重载
fun greet(name: String = "Guest") { println("Hello $name") } greet() // 输出:Hello Guest(使用默认值) -
命名参数 :提高可读性
fun log(time: String, message: String) { ... } log(message = "Error", time = "10:00") // 按名称传参,顺序无关
3. 函数类型分类
| 类型 | 说明 | 示例 |
|---|---|---|
| 顶层函数 | 直接定义在文件中,无类包裹 | fun topFunc() = println("顶层函数") |
| 成员函数 | 类内部的函数 | class A { fun member() {} } |
| 局部函数 | 函数内部定义的函数 | fun outer() { fun inner() {} } |
| 扩展函数 | 为现有类添加的函数 | fun String.hello() = "Hello $this" |
4. 特殊函数
-
递归函数
fun factorial(n: Int): Int = if (n <= 1) 1 else n * factorial(n - 1) println(factorial(5)) // 输出:120 -
尾递归函数 (
tailrec优化,避免栈溢出)tailrec fun fib(n: Int, a: Int = 0, b: Int = 1): Int = if (n == 0) a else fib(n - 1, b, a + b)
八、面向对象
1. 类与对象
// 类定义
class Person(
val id: Int, // 只读属性(val)
var name: String // 读写属性(var)
) {
// 初始化代码块
init {
require(id > 0) { "ID必须为正数" } // 参数校验
}
// 成员函数
fun introduce() = println("我是$name")
}
// 对象实例化
val person = Person(1, "Alice")
person.introduce() // 输出:我是Alice
2. 继承与重写
-
类默认
final,需用open修饰才能被继承open class Animal(val name: String) {
open fun sound() = println("$name 发出声音") // 可重写方法
}class Cat(name: String) : Animal(name) {
override fun sound() = println("$name 喵喵叫") // 重写方法
}Cat("小猫").sound() // 输出:小猫 喵喵叫
3. 接口
-
接口方法可带默认实现
interface Flyable {
fun fly() // 抽象方法
fun hover() { // 默认实现
println("悬停")
}
}class Bird : Flyable {
override fun fly() = println("鸟儿飞翔")
}val bird = Bird()
bird.fly() // 输出:鸟儿飞翔
bird.hover() // 输出:悬停(调用默认实现)
4. 抽象类
abstract class Shape {
abstract fun area(): Double // 抽象方法(无实现)
fun printArea() = println("面积:${area()}") // 具体方法
}
class Circle(val radius: Double) : Shape() {
override fun area() = Math.PI * radius * radius
}
Circle(2.0).printArea() // 输出:面积:12.566...
5. 数据类(data class)
-
自动生成
equals/hashCode/toString/copy/ 解构函数data class User(val id: Int, val name: String)
val u1 = User(1, "Alice")
val u2 = User(1, "Alice")
println(u1 == u2) // true(自动重写equals)
val u3 = u1.copy(name = "Bob") // 复制并修改属性
val (id, name) = u1 // 解构:id=1, name=Alice
6. 密封类(sealed class)
-
子类有限且已知,用于状态枚举
sealed class Result
object Loading : Result()
data class Success(val data: String) : Result()
data class Error(val msg: String) : Result()fun handle(result: Result) = when (result) {
is Loading -> println("加载中")
is Success -> println("成功:{result.data}") is Error -> println("失败:{result.msg}")
// 无需else,编译期检查所有子类
}
7. 单例(object)
object Config { // 全局唯一实例
val appName = "KotlinApp"
fun printInfo() = println("App: $appName")
}
Config.printInfo() // 直接调用,无需实例化
九、集合
1. 集合类型体系
| 不可变集合(只读) | 可变集合(可读写) | 说明 |
|---|---|---|
List |
MutableList |
有序可重复 |
Set |
MutableSet |
无序不可重复 |
Map |
MutableMap |
键值对映射 |
2. 集合创建
// 不可变集合(创建后不能修改)
val list = listOf(1, 2, 3)
val set = setOf("a", "b")
val map = mapOf("name" to "Alice", "age" to 20)
// 可变集合(可修改)
val mutableList = mutableListOf(1, 2)
mutableList.add(3)
3. 常用操作符
| 操作 | 说明 | 示例 |
|---|---|---|
filter |
过滤元素 | list.filter { it % 2 == 0 } |
map |
转换元素 | list.map { it * 2 } |
find |
查找第一个匹配元素 | list.find { it > 2 } |
any |
是否有元素满足条件 | list.any { it > 5 } |
all |
是否所有元素满足条件 | list.all { it > 0 } |
sum |
求和 | list.sum() |
示例:
val nums = listOf(1, 2, 3, 4, 5)
val result = nums
.filter { it % 2 == 0 } // [2,4]
.map { it * 10 } // [20,40]
.sum() // 60
十、Lambda 与高阶函数
1. Lambda 表达式
-
语法:
{ 参数列表 -> 函数体 }// 完整写法
val add: (Int, Int) -> Int = { a, b -> a + b }// 简化(参数唯一时用it)
val printNum: (Int) -> Unit = { println(it) }// 作为函数参数
listOf(1, 2).forEach { println(it) }
2. 高阶函数
-
定义:参数或返回值为函数的函数
// 函数作为参数
fun calculate(a: Int, b: Int, op: (Int, Int) -> Int) = op(a, b)// 调用:传入Lambda
val sum = calculate(3, 5) { x, y -> x + y } // 8
val product = calculate(3, 5) { x, y -> x * y } // 15
3. 内联函数(inline)
-
优化高阶函数性能,避免 Lambda 装箱
inline fun measureTime(block: () -> Unit) {
val start = System.currentTimeMillis()
block()
println("耗时:${System.currentTimeMillis() - start}ms")
}measureTime {
Thread.sleep(100) // 执行耗时操作
}
十一、泛型
1. 泛型类 / 接口
// 泛型类
class Box<T>(val content: T)
val intBox = Box(100)
val strBox = Box("Kotlin")
// 泛型接口
interface Repository<T> {
fun get(id: Int): T
}
class UserRepository : Repository<User> {
override fun get(id: Int) = User(id, "User$id")
}
2. 泛型约束
// 约束T必须是Number的子类
fun <T : Number> sum(a: T, b: T): Double {
return a.toDouble() + b.toDouble()
}
sum(1, 2) // 3.0(Int是Number子类)
3. 星投影(泛型通配符)
// 接受任意类型的List
fun printList(list: List<*>) {
list.forEach { println(it) }
}
十二、扩展
1. 扩展函数
-
为现有类添加方法,不修改原类
// 为String添加扩展函数
fun String.reverse(): String {
return this.reversed() // this指代调用者
}println("abc".reverse()) // 输出:cba
2. 扩展属性
-
无幕后字段,需显式实现 getter/setter
// 为Int添加扩展属性
val Int.isEven: Boolean
get() = this % 2 == 0println(4.isEven) // true
println(5.isEven) // false
十三、委托
1. 接口委托
-
实现接口时,将方法委托给其他对象
interface Printer {
fun print()
}class ConsolePrinter : Printer {
override fun print() = println("打印内容")
}// 委托给ConsolePrinter实现Printer接口
class OfficePrinter(printer: Printer) : Printer by printerOfficePrinter(ConsolePrinter()).print() // 输出:打印内容
2. 属性委托
-
延迟委托(
lazy) :首次访问时初始化val data by lazy { println("初始化中...") "初始化完成" } println(data) // 输出:初始化中... 初始化完成 println(data) // 直接输出:初始化完成(缓存) -
观察委托(
observable) :监听属性变化import kotlin.properties.Delegates var name by Delegates.observable("初始值") { prop, old, new -> println("${prop.name}从$old变为$new") } name = "新值" // 输出:name从初始值变为新值
十四、协程(异步编程)
1. 基础概念
-
轻量级线程,非阻塞,由
kotlinx-coroutines-core库提供import kotlinx.coroutines.*
fun main() = runBlocking { // 启动协程作用域
launch { // 启动新协程(子协程)
delay(1000) // 非阻塞延迟(类似sleep,但不阻塞线程)
println("World!")
}
println("Hello,") // 立即执行
}
// 输出:
// Hello,
// World!(1秒后)
2. 协程调度器
launch(Dispatchers.IO) { // IO密集型任务(网络/文件)
// 执行IO操作
}
launch(Dispatchers.Default) { // CPU密集型任务
// 执行计算
}
十五、其他特性
1. 区间(Range)
val range = 1..5 // 闭区间[1,5]
val range2 = 1 until 5 // 左闭右开[1,5)
val reversed = 5 downTo 1 // 倒序[5,1]
println(3 in range) // true
2. 序列(Sequence)
-
懒加载集合,适合大数据处理(避免中间集合)
val sequence = (1..1000).asSequence()
.filter { it % 2 == 0 }
.map { it * 2 }
.take(5) // 只处理前5个元素println(sequence.toList()) // [4,8,12,16,20]
十六、枚举类(Enum Class)
-
概念:定义固定数量的常量集合,可包含属性和方法。
enum class Direction(
val dx: Int, // 水平偏移
val dy: Int // 垂直偏移
) {
UP(0, -1),
DOWN(0, 1),
LEFT(-1, 0),
RIGHT(1, 0); // 注意分号// 枚举类方法 fun opposite(): Direction { return when (this) { UP -> DOWN DOWN -> UP LEFT -> RIGHT RIGHT -> LEFT } }}
fun main() {
val dir = Direction.UP
println(dir.dx) // 0
println(dir.opposite()) // DOWN
}
十七、注解(Annotation)
-
概念:为代码添加元数据,可通过反射获取,常用于框架(如 Retrofit、Dagger)。
// 定义注解
@Target(AnnotationTarget.FUNCTION) // 注解目标:函数
@Retention(AnnotationRetention.RUNTIME) // 保留到运行时
annotation class LogExecutionTime// 使用注解
@LogExecutionTime
fun heavyTask() {
Thread.sleep(100)
}// 通过反射处理注解(简化示例)
fun main() {
val method = ::heavyTask.javaMethod!!
if (method.isAnnotationPresent(LogExecutionTime::class.java)) {
val start = System.currentTimeMillis()
heavyTask()
println("耗时:${System.currentTimeMillis() - start}ms")
}
}
十八、反射(Reflection)
-
概念 :在运行时获取类 / 对象的信息(属性、方法等),需依赖
kotlin-reflect库。import kotlin.reflect.full.memberFunctions
import kotlin.reflect.full.memberPropertiesclass Person(val name: String, var age: Int) {
fun greet() = "Hello, $name"
}fun main() {
val person = Person("Alice", 20)
val kClass = person::class// 获取属性 val nameProp = kClass.memberProperties.find { it.name == "name" } println(nameProp?.get(person)) // Alice // 调用方法 val greetFunc = kClass.memberFunctions.find { it.name == "greet" } val result = greetFunc?.call(person) println(result) // Hello, Alice}
十九、类型别名(Type Alias)
-
概念:为复杂类型定义简短别名,提高可读性。
// 为函数类型定义别名
typealias IntProcessor = (Int) -> Int// 为泛型集合定义别名
typealias StringList = List<String>fun main() {
val double: IntProcessor = { it * 2 }
println(double(5)) // 10val names: StringList = listOf("Alice", "Bob")}
二十、作用域函数(Scope Functions)
Kotlin 提供 5 个作用域函数,用于在对象的作用域内执行代码块,简化操作:
| 函数 | 接收者引用 | 返回值 | 典型场景 |
|---|---|---|---|
let |
it |
lambda 结果 | 空安全处理、链式调用 |
run |
this |
lambda 结果 | 对象初始化 + 结果计算 |
with |
this |
lambda 结果 | 访问对象多个成员 |
apply |
this |
接收者本身 | 对象配置(设置属性) |
also |
it |
接收者本身 | 附加操作(日志、打印) |
示例:
data class User(var name: String, var age: Int)
fun main() {
// apply:配置对象(返回自身)
val user = User("", 0).apply {
name = "Alice"
age = 20
}
// let:空安全处理(返回lambda结果)
val userName: String? = user.name
val length = userName?.let {
println("Name: $it")
it.length
} ?: 0
// with:操作对象成员(返回结果)
val info = with(user) {
"Name: $name, Age: $age"
}
}
二十一、协程进阶
1. 协程取消与异常处理
import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
try {
repeat(1000) { i ->
println("计数:$i")
delay(500)
}
} finally {
// 取消后执行清理(非挂起函数)
println("协程取消,执行清理")
}
}
delay(1500) // 运行1.5秒
job.cancelAndJoin() // 取消并等待结束
}
2. 异步组合(async + awaitAll)
suspend fun fetchData(id: Int): String {
delay(1000)
return "数据$id"
}
fun main() = runBlocking {
val deferredList = listOf(1, 2, 3).map { id ->
async { fetchData(id) }
}
val results = deferredList.awaitAll() // 等待所有异步任务完成
println(results) // [数据1, 数据2, 数据3](总耗时~1秒)
}
二十二、Kotlin 与 Java 互操作细节
1. Kotlin 调用 Java
-
Java 的
null在 Kotlin 中视为可空类型 -
Java 的
void对应 Kotlin 的Unit// 调用Java的ArrayList
import java.util.ArrayList
val list = ArrayList<String>()
list.add("Kotlin")
2. Java 调用 Kotlin
-
Kotlin 顶层函数默认生成
FileNameKt类 -
可通过
@JvmName指定类名// Kotlin代码
@file:JvmName("StringUtils")
fun isEmpty(str: String?) = str.isNullOrEmpty()// Java代码中调用
StringUtils.isEmpty("test");
二十三、内联类(Inline Class)
-
概念:为基本类型创建包装类,避免运行时装箱开销(Kotlin 1.3+)。
@JvmInline
value class UserId(val id: Long) // 内联类fun printUserId(userId: UserId) {
println(userId.id)
}fun main() {
val id = UserId(123L)
printUserId(id) // 123(编译时直接使用Long,无额外对象)
}
Kotlin 全知识点梳理完毕!从基础到进阶,概念 + 示例全覆盖,助你快速上手实战~
点赞收藏,实操遇惑随时查阅!祝编码高效,技术进阶!