配置Kotlin when guards后仍提示需显式启用,求排查方案
问题:Kotlin 2.1.0 when guards 语法仍提示实验性功能未启用?
已将Android项目升级至Kotlin 2.1.0,并在build.gradle.kts中添加以下配置后同步项目:
kotlin { compilerOptions { freeCompilerArgs.add("-Xwhen-guards") } }
但使用when guards语法时:
fun processNotification(notification: Notification) { when (notification) { is Notification.Email if notification.isHighPriority -> println("Send high-priority email") is Notification.Email -> println("Send regular email") is Notification.SMS if notification.isInternational -> println("Send international SMS") is Notification.SMS -> println("Send local SMS") else -> println("Unknown notification type") } }
Android Studio(版本:Ladybug Feature Drop | 2024.2.2 Patch 1)仍提示错误:
The feature "when guards" is experimental and should be enabled explicitly
请问是否遗漏了关键配置?
解决方法
确保配置应用到目标模块
如果是多模块项目,仅在根项目的build.gradle.kts添加配置无效,需要在使用when guards语法的模块(比如app模块)的build.gradle.kts中重复添加相同的编译器参数配置。添加实验性功能启用声明
When guards属于实验性功能,仅开启编译器参数还不够,需在代码中显式声明:- 给单个函数添加注解:
@OptIn(ExperimentalWhenGuards::class) fun processNotification(notification: Notification) { // ... when 代码块 } - 或者在文件顶部添加文件级注解,作用于整个文件:
@file:OptIn(ExperimentalWhenGuards::class) // 你的代码 - 也可以在模块的
build.gradle.kts中全局配置,避免逐个添加注解:kotlin { compilerOptions { freeCompilerArgs.add("-Xwhen-guards") optIn.add("kotlin.ExperimentalWhenGuards") } }
- 给单个函数添加注解:
验证Kotlin插件版本
打开Android Studio的Settings > Plugins > Kotlin,确认插件版本与项目使用的Kotlin 2.1.0完全一致,若版本不匹配则点击更新后重启IDE。
内容的提问来源于stack exchange,提问作者Qk Lahpita
相关产品推荐
相关产品推荐

