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 [...]"
相关推荐
v***913013 分钟前
Spring+Quartz实现定时任务的配置方法
android·前端·后端
梵克之泪15 分钟前
【号码分离】从Excel表格、文本、word文档混乱文字中提取分离11位手机号出来,基于WPF的实现方案
开发语言·ui·c#
charlie11451419122 分钟前
面向C++程序员的JavaScript 语法实战学习4
开发语言·前端·javascript·学习·函数
夫唯不争,故无尤也22 分钟前
Python广播机制:张量的影分身术
开发语言·python
wilsend27 分钟前
Android Studio 2024版新建java项目和配置环境下载加速
android
qq_4798754329 分钟前
X-Macros(3)
java·开发语言
兰琛44 分钟前
Android Compose展示PDF文件
android·pdf
列逍1 小时前
深入理解 C++ 异常:从概念到实战的全面解析
开发语言·c++
java1234_小锋1 小时前
简述Mybatis的插件运行原理?
java·开发语言·mybatis
charlie1145141911 小时前
勇闯前后端Week2:后端基础——HTTP与REST
开发语言·网络·笔记·网络协议·学习·http