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 [...]"
相关推荐
lin62534221 天前
Android右滑解锁UI,带背景流动渐变动画效果
android·ui
weixin_462446231 天前
EasyExcel 动态修改模板 Sheet 名称:自定义 SheetWriteHandler 拦截器
java·开发语言·easyexcel
绝世唐门三哥1 天前
使用Intersection Observer js实现超出视口固定底部按钮
开发语言·前端·javascript
Ayu阿予1 天前
C++从源文件到可执行文件的过程
开发语言·c++
C++业余爱好者1 天前
JVM优化入门指南:JVM垃圾收集器(GC)介绍
java·开发语言·jvm
福尔摩斯张1 天前
基于C++的UDP网络通信系统设计与实现
linux·c语言·开发语言·网络·c++·tcp/ip·udp
Trouvaille ~1 天前
【Java篇】基石与蓝图::Object 类与抽象类的双重奏
java·开发语言·javase·抽象类·类与对象·基础入门·object类
卜锦元1 天前
Golang中make()和new()的区别与作用?
开发语言·后端·golang
Light601 天前
破局“数据孤岛”:构建业务、财务、指标三位一体的智能数据模型
java·大数据·开发语言
guygg881 天前
基于Matlab的压缩感知信道估计算法实现
开发语言·算法·matlab