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 ..."
相关推荐
江畔柳前堤1 小时前
roLabelImg 详细安装教程
开发语言·人工智能·后端·云原生
Wang's Blog2 小时前
Go-Zero 项目开发47:自研微服务框架的必要性与核心结构设计
开发语言·微服务·golang
白鸽(二般)2 小时前
MinIO Java Client API
java·开发语言
hPw0eKIqD2 小时前
C++ 模板参数推导问题小记(非推导上下文)
开发语言·c++
临床数据科学和人工智能兴趣组3 小时前
要使用 R Markdown,首先需要安装 R 和 RStudio,接着安装 rmarkdown 包
开发语言·数据挖掘·数据分析·r语言·r语言-4.2.1
Nebula嵌入式3 小时前
【C语言】09-深入解析main函数
linux·c语言·开发语言·嵌入式
神罚天下ET5 小时前
c# ACME client (补充)
开发语言·c#
plainGeekDev5 小时前
工厂模式 → Hilt
android·java·kotlin
小灰灰搞电子5 小时前
Qt 实现魔法导航菜单源码分享
开发语言·qt
持敬chijing5 小时前
Python概述
开发语言·python