Kotlin 2.1 升级实践与问题排查记录
前言
随着 Kotlin 2.1 版本的发布,我们的技术团队近期完成了从 Kotlin 1.9.23 到 2.1.10 的版本升级工作。本文旨在记录此次升级过程中遇到的主要问题及其解决方案,为后续类似升级提供参考。
核心升级内容
1. Kotlin 版本升级
升级路径:1.9.23 → 2.1.10
关键变更:
- 配套升级 KSP (Kotlin Symbol Processing) 版本
- 部分模块出现语法兼容性问题
解决方案: 对于存在兼容性问题的模块,我们采取了临时降级策略以确保快速上线:
// 问题模块使用 1.9 兼容模式
android {
kotlinOptions {
languageVersion = "1.9"
freeCompilerArgs += ['-Xjvm-default=all']
}
}
全局配置管理: 为确保各子模块版本一致性,我们在根项目中添加了以下强制配置:
// 全局锁死
// for compile options
subprojects {
afterEvaluate {
if (project.hasProperty("SKIP_COMPILE_CONFIG")) { // 子模块不允许覆盖
logger.warn("skip override project compile config, p = ${project}")
return
}
def jtc = 11
def jv = JavaVersion.toVersion(jtc)
def jt = "11"
def klv = "2.0"
if (project.plugins.hasPlugin("com.android.application") || project.plugins.hasPlugin("com.android.library")) {
android.compileOptions {
sourceCompatibility jv
targetCompatibility jv
}
}
project.tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
kotlinOptions {
jvmTarget = jt
if (languageVersion == null) {
languageVersion = klv
} else {
logger.error("$project kotlinOptions.languageVersion is set to $languageVersion")
}
if (freeCompilerArgs.contains("-language-version")) {
// throw new RuntimeException("project[$project] freeCompilerArgs contains -language-version")
}
freeCompilerArgs += ['-Xjvm-default=all']
}
}
}
}
2. Compose 编译插件升级
重要变更:
- Compose 编译器现在与 Kotlin 版本绑定
- 移除了原有的独立版本配置
// 原先的配置
// composeOptions {
// kotlinCompilerExtensionVersion = rootProject.ext.get("compose_version").toString()
// }
新版配置方式: 采用版本目录(TOML)管理:
[versions]
compose_compiler = "2.1.10"
[plugins]
compose_compiler = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "compose_compiler" }
模块级应用:
plugins {
id 'com.android.library'
id 'kotlin-android'
id 'kotlin-kapt'
alias(libs.plugins.compose.compiler)
}
3. R8 工具升级
问题现象:
- kotlin 升级后出现 Dex 处理任务异常
- Debug 构建出现大量堆栈错误日志
- Release 构建表现正常
解决方案: 将 R8 版本从 8.2.47 升级至 8.7.18 后问题解决。
4. Kotlinx-serialization 性能问题
升级情况:
- 1.6.3 → 1.8.0
发现问题:
- 灰度发布后监测到应用启动耗时显著增加
排查过程: 通过逐步回滚变更,最终定位到序列化库升级是性能下降的主因。
临时方案: 回退至 1.6.3 版本,后续计划专项排查新版本性能问题。
经验总结
- 监控先行:建立完善的编译耗时、运行时性能监控体系
- 渐进升级:采用灰度发布策略,控制影响范围
- 版本管理:统一版本控制,避免分散配置
- 问题定位:掌握科学的回退排查方法
- 文档记录:详细记录问题现象和解决方案
此次升级过程中,我们深刻体会到基础设施升级对项目稳定性的重大影响。后续我们将进一步完善升级验证流程,确保技术迭代平稳进行。