0%

Google IO 2023记录 - Android版本Kotlin的新动态

说是新动态, 其实内容大家基本上都见过了

前言

2017 Kotlin成为Android官方支持语言

2019 Android开发Kotlin优先, 文档和库都是主要为Kotlin设计的

如今, Play商店排行前1000中, 有95%使用Kotlin (包括依赖)

70%应用本身使用Kotlin

55%使用Kotlin协程

Jetpack Compose 是完全为Kotlin设计的, 充分利用了Kotlin语言特性

Google自2019将Kotlin普遍用于Android开发, 自2022年起将Kotlin用于服务端开发

Google中数以千计的开发者编写Kotlin代码, 版本控制系统有超过1500万行Kotlin代码

Kotlin 2.0编译器 (K2编译器)

性能提升两倍

路线图

See also

https://blog.jetbrains.com/kotlin/2023/02/k2-kotlin-2-0/

https://blog.jetbrains.com/kotlin/2021/10/the-road-to-the-k2-compiler/

测试K2编译器(Kotlin1.8.20)

使用命令行参数:

-language-version 2.0

或者使用Gradle配置:

1
2
3
4
5
6
7
kotlin {
sourceSets.all {
languageSettings {
languageVersion = "2.0"
}
}
}

See also

https://kotlinlang.org/docs/whatsnew1820.html

Gradle Kotlin DSL

从Android Studio Giraffe开始, 项目模板将默认使用Gradle Kotlin DSL

和GroovyDSL相比, 得益于使用更多的静态类型, Gradle Kotlin DSL可以有更多的代码提示

并且可以通过转到定义查看更多文档

See also

https://docs.gradle.org/current/userguide/kotlin_dsl.html

Gradle版本目录(实验性功能)

使用TOML集中化管理依赖, 更加简明易维护

示例ibs.versions.toml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
[versions]
com-android-application = "8.1.0-alpha11"
org-jetbrains-kotlin-android = "1.7.20"
core-ktx = "1.9.0"
junit = "4.13.2"
androidx-test-ext-junit = "1.1.3"
espresso-core = "3.4.0"
lifecycle-runtime-ktx = "2.3.1"
activity-compose = "1.5.1"
compose-bom = "2022.10.00"

[libraries]
core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "core-ktx" }
junit = { group = "junit", name = "junit", version.ref = "junit" }

See also

https://docs.gradle.org/current/userguide/platforms.html#sec:sharing-catalogs

https://developer.android.com/build/migrate-to-catalogs

Kotlin Symbol Processing (KSP)

kapt (Kotlin Annotation Processing Tool)

由kotlin代码生成Java stubs, 再由Java Annotation Processors处理

存在问题: 速度慢

ksp: kapt替代方案

  • 直接分析Kotlin代码
  • 速度提升两倍
  • 更好支持Kotlin特性(如可空类型)
  • 支持多平台项目

迁移到ksp

  1. 添加ksp插件
1
2
3
4
5
6
7
8
9
// 顶层声明插件版本
plugins {
id 'com.google.devtools.ksp' version '1.8.10-1.0.9' apply false
}

// 应用插件
plugins {
id 'com.google.devtools.ksp'
}
  1. 以ksp替换kapt
1
2
3
4
dependencies {
kapt 'androidx.room:room-compiler:2.5.0'
ksp 'androidx.room:room-compiler:2.5.0'
}

注意, 并非所有支持kapt的库都支持ksp, 需要库作者适配

目前支持ksp的项目: Room, Glide, Moshi, etc.

See also

https://developer.android.com/build/migrate-to-ksp

Kotlin Multiplatform (Beta)

使用Kotlin Multiplatform for Mobile(KMM)在Android和iOS中共享代码

See also

https://kotlinlang.org/docs/multiplatform-mobile-getting-started.html

一些Jetpack库开始支持Kotlin Multiplatform:

  • Annotations 1.7.0-alpha2
  • Collections 1.3.0-alpha4
  • DataStore 1.1.0-alpha3

See also

https://developer.android.com/kotlin/multiplatform?hl=zh-cn

https://android-developers.googleblog.com/2023/04/whats-new-in-jetpack-multiplatform.html