android中gradle的kotlin编译配置选项

一、编译配置

1、Android中的配置

使用如下方式开启在Android中的gradle的kotlin编译配置:

该配置在其余平台不可用

groovy 复制代码
android {
   ...
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_17
        targetCompatibility JavaVersion.VERSION_17
    }
    kotlinOptions {
        jvmTarget = '1.8'
//        freeCompilerArgs.add("-Xexport-kdoc")
        setFreeCompilerArgs(["-Xcontext-receivers"])
//setFreeCompilerArgs(["-Xexport-kdoc","-Xcontext-receivers","-opt-in=org.mylibrary.OptInAnnotation"])
    }
    //如下方式会报错
    //tasks.withType(KotlinCompile::class).all {
//    kotlinOptions.freeCompilerArgs = listOf("-Xcontext-receivers")
//}

...

}

以上配置会开启Kotlin/JVM 的上下文接收者原型功能,否则该功能不可用,开启后编码可以使用以下代码:

kotlin 复制代码
interface LoggingContext {
    val log: Logger // This context provides a reference to a logger 
}

context(LoggingContext)
fun startBusinessOperation() {
    // You can access the log property since LoggingContext is an implicit receiver
    log.info("Operation has started")
}

fun test(loggingContext: LoggingContext) {
    with(loggingContext) {
        // You need to have LoggingContext in a scope as an implicit receiver
        // to call startBusinessOperation()
        startBusinessOperation()
    }
}

传递参数的发过誓可以直接在里面写setFreeCompilerArgs(["-opt-in=org.mylibrary.OptInAnnotation"])

2、其余平台的配置

除了上述配置还可以使用以下配置,该配置可以在其余平台使用:

groovy 复制代码
android {
}
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
    sourceCompatibility = JavaVersion.VERSION_1_8
    targetCompatibility = JavaVersion.VERSION_1_8

    kotlinOptions {
        jvmTarget = '1.8'
        apiVersion = '1.1'
        languageVersion = '1.1'
    }
}

二、参考链接:

  1. Kotlin 1.6.20 的新特性
  2. Kotlin Gradle plugin 中的编译器选项
  3. IDE highlighting: False positive error "Context receivers should be enabled explicitly"
  4. compileKotlin block in build.gradle file throws error "Could not find method compileKotlin() for arguments ..."
相关推荐
人间凡尔赛41 分钟前
Next.js 16 生产级实战:Cache Components + View Transitions 完整指南
开发语言·javascript·ecmascript
稚南城才子,乌衣巷风流4 小时前
函数:编程中的核心概念
开发语言·前端·javascript
阿米亚波4 小时前
【C++】流式数据输入处理(不完全整理)
开发语言·c++·笔记
大模型码小白5 小时前
JAVA 集合框架进阶:List 与 Set 的深度解析与实战
java·开发语言·人工智能·windows·语言模型·list·ai编程
皓月斯语6 小时前
【C++基础】三目运算符
开发语言·数据结构·c++
初願致夕霞6 小时前
C++懒汉单例设计详解
服务器·开发语言·c++
Xzaveir6 小时前
不要用一个状态表示“号码已认证”:企业号码身份的四域模型
android·人工智能
脱胎换骨-军哥6 小时前
C++分布式系统设计:从通信引擎到分布式共识
开发语言·c++·分布式
(Charon)7 小时前
【C++】手写 MySQL 连接池(二):同步连接的获取、加锁与释放
android
脱胎换骨-军哥7 小时前
C++零成本抽象理论深度拆解:现代C++如何在不牺牲性能的前提下提供高级语法封装
java·开发语言·c++