一、编译配置
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'
}
}