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 [...]"
相关推荐
java1234_小锋8 分钟前
PyTorch2 Python深度学习 - 初识PyTorch2,实现一个简单的线性神经网络
开发语言·python·深度学习·pytorch2
胡萝卜3.09 分钟前
C++面向对象继承全面解析:不能被继承的类、多继承、菱形虚拟继承与设计模式实践
开发语言·c++·人工智能·stl·继承·菱形继承·组合vs继承
Violet_YSWY14 分钟前
将axios、async、Promise联系在一起讲一下&讲一下.then 与其关系
开发语言·前端·javascript
Tom4i15 分钟前
基于 Launcher3 的 iOS 风格桌面 04 拖拽和移位
android
2501_9151063219 分钟前
iOS 反编译防护工具与实战组合 从静态侦察到 IPA 成品加固的工程化路径
android·ios·小程序·https·uni-app·iphone·webview
luoganttcc35 分钟前
用Python的trimesh库计算3DTiles体积的具体代码示例
开发语言·python·3d
我爱画页面40 分钟前
vue3封装table组件及属性介绍
开发语言·javascript·ecmascript
逻极40 分钟前
Next.js vs Vue.js:2025年全栈战场,谁主沉浮?
开发语言·javascript·vue.js·reactjs
Python私教1 小时前
C 语言进制转换全景指南
c语言·开发语言·arm开发
caimo1 小时前
Java无法访问网址出现Timeout但是浏览器和Postman可以
java·开发语言·postman