Kotlin v2.1.20 发布,标准库又有哪些变化?

发布于:2025-03-21 ⋅ 阅读:(19) ⋅ 点赞:(0)

大家吼哇!就在三小时前,Kotlin v2.1.20 发布了,更新的内容也已经在官网上更新:What’s new in Kotlin 2.1.20
我粗略地看了一下,下面为大家选出一些我比较感兴趣、且你可能也会感兴趣的内容。

注意!这里只选了一些标准库中的一些API之类的变化,不会包括诸如编译器变动、工具(例如Gradle)变化等。

Atomic API

现在,在 Kotlin 的标准库中可以使用原子类啦!在之前,想要使用原子类型,要么只能在 JVM 平台中使用,要么需要自己手动实现,很麻烦,现在 Kotlin common API 中为标准库添加了 kotlin.concurrent.atomics 包,其中包括了一些原子类型。
现在,你可以在任何Kotlin支持的平台上使用原子类型了!

以下是官方示例:

@OptIn(ExperimentalAtomicApi::class)
suspend fun main() {
    // Initializes the atomic counter for processed items
    var processedItems = AtomicInt(0)
    val totalItems = 100
    val items = List(totalItems) { "item$it" }
    // Splits the items into chunks for processing by multiple coroutines
    val chunkSize = 20
    val itemChunks = items.chunked(chunkSize)
    coroutineScope {
        for (chunk in itemChunks) {
            launch {
                for (item in chunk) {
                    println("Processing $item in thread ${Thread.currentThread()}")
                    processedItems += 1 // Increment counter atomically
                }
            }
        }
    }

如果你熟悉Java中的原子API,那么对这些新增类型的使用肯定不会陌生。而提到 Java,这些原子类型也一如既往地提供了与 Java 类型互换的API asJavaAtomicasKotlinAtomic

@OptIn(ExperimentalAtomicApi::class)
fun main() {
    // Converts Kotlin AtomicInt to Java's AtomicInteger
    val kotlinAtomic = AtomicInt(42)
    val javaAtomic: AtomicInteger = kotlinAtomic.asJavaAtomic()
    println("Java atomic value: ${javaAtomic.get()}")
    // Java atomic value: 42

    // Converts Java's AtomicInteger back to Kotlin's AtomicInt
    val kotlinAgain: AtomicInt = javaAtomic.asKotlinAtomic()
    println("Kotlin atomic value: ${kotlinAgain.load()}")
    // Kotlin atomic value: 42
}

UUID

这个版本中,标准库针对之前版本增加的 UUID 类型进行了一些增强和调整。

简单来说:

  1. 改善了 parse() 的效果,现在不带 - (破折号) 的 UUID 也能解析了。
  2. 增加了一些语义更明确的函数:parseHexDash(), toHexDashString()
  3. UUID 实现 Comparable,也就是说现在 UUID 是可以排序或者进行比较的了,比如使用 sorted() 或使用操作符 <> 等。

以下是官方示例:

@OptIn(ExperimentalUuidApi::class)
fun main() {
    // parse() accepts a UUID in a plain hexadecimal format
    val uuid = Uuid.parse("550e8400e29b41d4a716446655440000")

    // Converts it to the hex-and-dash format
    val hexDashFormat = uuid.toHexDashString()
 
    // Outputs the UUID in the hex-and-dash format
    println(hexDashFormat)

    // Outputs UUIDs in ascending order
    println(
        listOf(
            uuid,
            Uuid.parse("780e8400e29b41d4a716446655440005"),
            Uuid.parse("5ab88400e29b41d4a716446655440076")
        ).sorted()
    )
   }

新的时间跟踪API

在 2.1.20 中,添加了一些原本只在 kotlinx-datetime 中才有的API。这下子在标准库中操作时间终于要变得更简单了,还不需要额外的依赖。

KMP库狂喜!

  • 引入了同 kotlinx.datetime.Clock 的接口 kotlin.time.Clock
  • 引入了同 kotlinx.datetime.Instant 的接口 kotlin.time.Instant

当然,一如既往,它们也有与 Java 和 JS 进行相互转化的API:

  • JVM 平台中 InstanttoKotlinInstant()toJavaInstant()
  • JS 平台中使用 Instant.toJSDate() 可以将 Instant 转化为 JS 的 Date

以下是官方示例:

import kotlin.time.*

@OptIn(ExperimentalTime::class)
fun main() {

    // Get the current moment in time
    val currentInstant = Clock.System.now()
    println("Current time: $currentInstant")

    // Find the difference between two moments in time
    val pastInstant = Instant.parse("2023-01-01T00:00:00Z")
    val duration = currentInstant - pastInstant

    println("Time elapsed since 2023-01-01: $duration")
}

结尾

以上就是主要的标准库变化啦!其他的变化内容也有不少,感兴趣的话可以去官网了解喔,这些变化里我最喜欢的就是 atomic API 和 time API 进入标准库了,为 KMP 库作者省了不少事儿呢。

不说了,我又得跟进更新我的编译器插件 kotlin-suspend-transform-compiler-plugin、继续跟编译器插件搏斗了,我们下次见,爱你♥