You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Kotlin Notebooks中正确使用measureTime?

Kotlin Notebook中measureTime的Opt-in问题解决方法

当你在Kotlin Notebook中使用measureTime时,遇到的报错提示要求声明使用实验性API,而你之前添加的@ExperimentalTime注解是用来标记自己的代码为实验性的,并非用来授权使用标准库的实验性API。以下是几种可行的解决方式:

方式一:文件级别Opt-in声明(推荐)

在代码块顶部添加@file:OptIn注解,让整个代码块都能使用该实验性API:

@file:OptIn(kotlin.time.ExperimentalTime::class)

import kotlin.time.measureTime

val timeTaken = measureTime {
    Thread.sleep(100)
}
println(timeTaken)

方式二:局部Opt-in声明

如果只需要在特定代码段启用,可以在使用measureTime的变量或表达式上添加@OptIn注解:

import kotlin.time.measureTime
import kotlin.time.ExperimentalTime

@OptIn(ExperimentalTime::class)
val timeTaken = measureTime {
    Thread.sleep(100)
}
println(timeTaken)

或者直接在measureTime调用前标注:

import kotlin.time.measureTime
import kotlin.time.ExperimentalTime

val timeTaken = @OptIn(ExperimentalTime::class) measureTime {
    Thread.sleep(100)
}
println(timeTaken)

方式三:全局启用(适合频繁使用场景)

如果你的Notebook经常用到实验性时间API,可以在Kotlin编译器参数中添加-Xopt-in=kotlin.time.ExperimentalTime:

  • IntelliJ Kotlin Notebook:通过设置界面找到Kotlin编译器选项添加该参数;
  • Jupyter Kotlin Kernel:启动时配置对应参数。

内容的提问来源于stack exchange,提问作者Soid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 19:58:15