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

大家吼哇!就在三小时前,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支持的平台上使用原子类型了!

以下是官方示例:

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

Kotlin 复制代码
@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() 或使用操作符 <> 等。

以下是官方示例:

Kotlin 复制代码
@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

以下是官方示例:

Kotlin 复制代码
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、继续跟编译器插件搏斗了,我们下次见,爱你♥

相关推荐
future_studio20 分钟前
聊聊 Unity(小白专享、C# 小程序 之 加密存储)
开发语言·小程序·c#
小糖学代码20 分钟前
MySQL:14.mysql connect
android·数据库·mysql·adb
m0_7369270437 分钟前
Spring Boot自动配置与“约定大于配置“机制详解
java·开发语言·后端·spring
feiyangqingyun1 小时前
Qt项目作品在苹果macos上编译运行效果/视频监控系统/物联网平台等
开发语言·qt·macos
你不是我我2 小时前
【Java 开发日记】我们来说一说 Redisson 的原理
java·开发语言
kk”2 小时前
C++ stack 和 queue
开发语言·c++
Matlab仿真实验室2 小时前
基于Matlab实现双目图计算深度图
开发语言·数码相机·matlab·双目图计算深度图
QT 小鲜肉2 小时前
【数据结构与算法基础】05. 栈详解(C++ 实战)
开发语言·数据结构·c++·笔记·学习·算法·学习方法
老K的Java兵器库2 小时前
Collections 工具类 15 个常用方法源码:sort、binarySearch、reverse、shuffle、unmodifiableXxx
java·开发语言·哈希算法
武子康2 小时前
Java-153 深入浅出 MongoDB 全面的适用场景分析与选型指南 场景应用指南
java·开发语言·数据库·mongodb·性能优化·系统架构·nosql