Kotlin基础语法 #

一、Kotlin简介 #

Kotlin是一种运行在Java虚拟机上的静态类型编程语言,由JetBrains开发。2017年,Google宣布Kotlin成为Android官方开发语言。

1.1 Kotlin的特点 #

  • 简洁:减少样板代码,提高开发效率
  • 安全:空安全设计,避免NullPointerException
  • 互操作:与Java完全兼容,可以混合使用
  • 现代:支持Lambda、协程等现代特性

1.2 为什么选择Kotlin #

特性 Kotlin Java
空安全 内置支持 需要注解
扩展函数 支持 不支持
数据类 data class 需要生成getter/setter
协程 原生支持 需要第三方库
智能类型转换 支持 需要显式转换

二、变量与数据类型 #

2.1 变量声明 #

kotlin
// val - 不可变变量(只读,相当于final)
val name = "Kotlin"
val age: Int = 10

// var - 可变变量
var count = 0
count = 1

// 类型推断
val message = "Hello"  // 自动推断为String
val number = 42        // 自动推断为Int

// 显式类型声明
val price: Double = 19.99
val isActive: Boolean = true

2.2 基本数据类型 #

类型 说明 示例
Byte 8位整数 val b: Byte = 1
Short 16位整数 val s: Short = 10
Int 32位整数 val i: Int = 100
Long 64位整数 val l: Long = 1000L
Float 32位浮点数 val f: Float = 3.14f
Double 64位浮点数 val d: Double = 3.14159
Char 字符 val c: Char = ‘A’
Boolean 布尔值 val b: Boolean = true
String 字符串 val s: String = “Hello”

2.3 字符串 #

kotlin
// 字符串模板
val name = "World"
val greeting = "Hello, $name!"
val expression = "2 + 2 = ${2 + 2}"

// 多行字符串
val text = """
    这是
    多行
    字符串
""".trimIndent()

// 原始字符串
val json = """
    {
        "name": "Kotlin",
        "version": 1.9
    }
""".trimIndent()

2.4 空安全 #

kotlin
// 可空类型
var name: String? = "Kotlin"
name = null  // 允许为null

// 非空类型
var nonNullName: String = "Kotlin"
// nonNullName = null  // 编译错误

// 安全调用操作符 ?.
val length = name?.length  // 如果name为null,返回null

// Elvis操作符 ?:
val len = name?.length ?: 0  // 如果name为null,返回0

// 非空断言 !!(谨慎使用)
val forceLength = name!!.length  // 如果name为null,抛出NPE

// 安全转换
val number: Int? = "123" as? Int

三、运算符 #

3.1 算术运算符 #

kotlin
val a = 10
val b = 3

val sum = a + b       // 加法: 13
val diff = a - b      // 减法: 7
val product = a * b   // 乘法: 30
val quotient = a / b  // 除法: 3
val remainder = a % b // 取余: 1

// 范围
val range = 1..10     // 1到10
val until = 1 until 10  // 1到9
val downTo = 10 downTo 1  // 10到1

3.2 比较运算符 #

kotlin
val x = 5
val y = 10

x == y   // 等于
x != y   // 不等于
x < y    // 小于
x > y    // 大于
x <= y   // 小于等于
x >= y   // 大于等于

// 区间检查
x in 1..10  // x是否在1到10之间
x !in 1..10 // x是否不在1到10之间

3.3 逻辑运算符 #

kotlin
val a = true
val b = false

val and = a && b  // 与
val or = a || b   // 或
val not = !a      // 非

四、控制流 #

4.1 条件语句 #

kotlin
// if表达式
val max = if (a > b) a else b

// if-else if-else
val score = 85
val grade = if (score >= 90) {
    "A"
} else if (score >= 80) {
    "B"
} else if (score >= 70) {
    "C"
} else {
    "D"
}

// when表达式(类似switch)
val day = 1
val dayName = when (day) {
    1 -> "星期一"
    2 -> "星期二"
    3 -> "星期三"
    4 -> "星期四"
    5 -> "星期五"
    6, 7 -> "周末"
    in 8..100 -> "无效"
    else -> "未知"
}

// when类型检查
val obj: Any = "Hello"
when (obj) {
    is Int -> println("整数: $obj")
    is String -> println("字符串: $obj")
    is Double -> println("双精度: $obj")
    else -> println("未知类型")
}

4.2 循环语句 #

kotlin
// for循环
for (i in 1..5) {
    println(i)
}

for (i in 1 until 5) {
    println(i)
}

for (i in 5 downTo 1) {
    println(i)
}

for (i in 1..10 step 2) {
    println(i)
}

// 遍历集合
val list = listOf("A", "B", "C")
for (item in list) {
    println(item)
}

// 带索引遍历
for ((index, value) in list.withIndex()) {
    println("$index: $value")
}

// while循环
var i = 0
while (i < 5) {
    println(i)
    i++
}

// do-while循环
var j = 0
do {
    println(j)
    j++
} while (j < 5)

// 循环控制
for (i in 1..10) {
    if (i == 3) continue  // 跳过本次循环
    if (i == 7) break     // 跳出循环
    println(i)
}

五、函数 #

5.1 函数定义 #

kotlin
// 基本函数
fun add(a: Int, b: Int): Int {
    return a + b
}

// 单表达式函数
fun add(a: Int, b: Int) = a + b

// 无返回值
fun greet(name: String): Unit {
    println("Hello, $name!")
}

// 省略Unit
fun greet(name: String) {
    println("Hello, $name!")
}

5.2 参数默认值 #

kotlin
fun greet(name: String, greeting: String = "Hello") {
    println("$greeting, $name!")
}

greet("Kotlin")              // Hello, Kotlin!
greet("Kotlin", "Hi")        // Hi, Kotlin!
greet(greeting = "Hi", name = "Kotlin")  // 命名参数

5.3 可变参数 #

kotlin
fun sum(vararg numbers: Int): Int {
    return numbers.sum()
}

sum(1, 2, 3)           // 6
sum(1, 2, 3, 4, 5)     // 15

// 展开数组
val nums = intArrayOf(1, 2, 3)
sum(*nums)             // 6

5.4 扩展函数 #

kotlin
// 为String添加扩展函数
fun String.isEmail(): Boolean {
    return this.contains("@")
}

val email = "test@example.com"
email.isEmail()  // true

// 扩展属性
val String.firstChar: Char
    get() = this[0]

"Kotlin".firstChar  // 'K'

5.5 高阶函数 #

kotlin
// 函数类型
val add: (Int, Int) -> Int = { a, b -> a + b }

// 高阶函数
fun calculate(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
    return operation(a, b)
}

calculate(5, 3) { x, y -> x + y }  // 8
calculate(5, 3) { x, y -> x * y }  // 15

// 常用高阶函数
val numbers = listOf(1, 2, 3, 4, 5)

// map - 映射
numbers.map { it * 2 }  // [2, 4, 6, 8, 10]

// filter - 过滤
numbers.filter { it > 2 }  // [3, 4, 5]

// find - 查找
numbers.find { it > 3 }  // 4

// any - 是否存在
numbers.any { it > 5 }  // false

// all - 是否全部满足
numbers.all { it > 0 }  // true

// reduce - 累积
numbers.reduce { acc, n -> acc + n }  // 15

// forEach - 遍历
numbers.forEach { println(it) }

5.6 Lambda表达式 #

kotlin
// Lambda语法
val sum = { a: Int, b: Int -> a + b }

// 简化写法
val list = listOf(1, 2, 3, 4, 5)
list.filter { it > 2 }  // it是隐式参数

// 多行Lambda
list.map { 
    val doubled = it * 2
    doubled.toString()
}

六、类与对象 #

6.1 类定义 #

kotlin
class Person {
    // 属性
    var name: String = ""
    var age: Int = 0
    
    // 方法
    fun introduce() {
        println("我是$name,今年$age岁")
    }
}

// 使用
val person = Person()
person.name = "Kotlin"
person.age = 10
person.introduce()

6.2 构造函数 #

kotlin
// 主构造函数
class Person(val name: String, var age: Int) {
    fun introduce() {
        println("我是$name,今年$age岁")
    }
}

// 初始化块
class Person(val name: String) {
    var age: Int = 0
    
    init {
        println("创建Person: $name")
    }
}

// 次构造函数
class Person(val name: String) {
    var age: Int = 0
    
    constructor(name: String, age: Int) : this(name) {
        this.age = age
    }
}

6.3 数据类 #

kotlin
data class User(val id: Int, val name: String, val email: String)

// 自动生成equals、hashCode、toString、copy
val user1 = User(1, "Kotlin", "kotlin@example.com")
val user2 = user1.copy(name = "Java")

println(user1)  // User(id=1, name=Kotlin, email=kotlin@example.com)
println(user1 == user2)  // false

// 解构声明
val (id, name, email) = user1

6.4 密封类 #

kotlin
sealed class Result {
    data class Success(val data: String) : Result()
    data class Error(val message: String) : Result()
    object Loading : Result()
}

fun handleResult(result: Result) {
    when (result) {
        is Result.Success -> println("成功: ${result.data}")
        is Result.Error -> println("错误: ${result.message}")
        Result.Loading -> println("加载中...")
    }
}

6.5 枚举类 #

kotlin
enum class Direction {
    NORTH, SOUTH, EAST, WEST
}

enum class Color(val rgb: Int) {
    RED(0xFF0000),
    GREEN(0x00FF00),
    BLUE(0x0000FF)
}

6.6 对象与伴生对象 #

kotlin
// 单例对象
object Database {
    fun connect() {
        println("连接数据库")
    }
}

Database.connect()

// 伴生对象(类似静态成员)
class Utils {
    companion object {
        const val VERSION = "1.0"
        
        fun log(message: String) {
            println(message)
        }
    }
}

Utils.log("Hello")
println(Utils.VERSION)

七、接口与继承 #

7.1 接口 #

kotlin
interface Clickable {
    fun click()
    
    fun show() {
        println("显示")
    }
}

class Button : Clickable {
    override fun click() {
        println("按钮被点击")
    }
}

7.2 继承 #

kotlin
// 父类需要使用open关键字
open class Animal(val name: String) {
    open fun sound() {
        println("$name 发出声音")
    }
}

class Dog(name: String) : Animal(name) {
    override fun sound() {
        println("$name 汪汪叫")
    }
}

7.3 抽象类 #

kotlin
abstract class Shape {
    abstract fun area(): Double
    
    fun info() {
        println("这是一个形状")
    }
}

class Rectangle(val width: Double, val height: Double) : Shape() {
    override fun area(): Double {
        return width * height
    }
}

八、集合 #

8.1 List #

kotlin
// 不可变List
val list = listOf(1, 2, 3)
val mixedList = listOf(1, "two", 3.0)

// 可变List
val mutableList = mutableListOf(1, 2, 3)
mutableList.add(4)
mutableList.removeAt(0)

// 访问
list[0]          // 1
list.getOrNull(5)  // null
list.first()     // 1
list.last()      // 3

8.2 Set #

kotlin
// 不可变Set
val set = setOf(1, 2, 3, 2, 1)  // {1, 2, 3}

// 可变Set
val mutableSet = mutableSetOf(1, 2, 3)
mutableSet.add(4)
mutableSet.remove(1)

8.3 Map #

kotlin
// 不可变Map
val map = mapOf("a" to 1, "b" to 2)

// 可变Map
val mutableMap = mutableMapOf("a" to 1, "b" to 2)
mutableMap["c"] = 3
mutableMap.remove("a")

// 访问
map["a"]         // 1
map.getValue("a")  // 1
map.getOrDefault("c", 0)  // 0

九、协程基础 #

9.1 启动协程 #

kotlin
import kotlinx.coroutines.*

// 在Activity中使用
class MainActivity : AppCompatActivity() {
    private val scope = MainScope()
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        scope.launch {
            val result = withContext(Dispatchers.IO) {
                // 执行耗时操作
                fetchData()
            }
            // 更新UI
            textView.text = result
        }
    }
    
    override fun onDestroy() {
        super.onDestroy()
        scope.cancel()
    }
}

9.2 常用协程构建器 #

kotlin
// launch - 启动新协程,不返回结果
scope.launch {
    delay(1000)
    println("Hello")
}

// async - 启动新协程,返回Deferred
val deferred = scope.async {
    delay(1000)
    "Result"
}
val result = deferred.await()

// withContext - 切换上下文
withContext(Dispatchers.IO) {
    // 在IO线程执行
}

9.3 调度器 #

调度器 用途
Dispatchers.Main 主线程,用于UI操作
Dispatchers.IO IO线程,用于网络、文件操作
Dispatchers.Default 默认线程,用于CPU密集型任务
Dispatchers.Unconfined 不指定线程

十、总结 #

本章介绍了Kotlin的核心语法:

  1. 变量与数据类型
  2. 运算符
  3. 控制流语句
  4. 函数与高阶函数
  5. 类与对象
  6. 接口与继承
  7. 集合操作
  8. 协程基础

Kotlin是一门现代、简洁、安全的语言,非常适合Android开发。掌握了Kotlin基础后,我们就可以开始学习Android的四大组件了。

最后更新:2026-03-26