12.2.7 SAM-with-receiver 编译器插件

原文链接: https://kotlinlang.org/docs/sam-with-receiver-plugin.html

12.2.7 SAM-with-receiver 编译器插件

sam-with-receiver 编译器插件会把带注解的 Java “单一抽象方法”(SAM)接口方法的第一个参数变成 Kotlin 中的接收者。只有在把该 SAM 接口作为 Kotlin lambda 传入时,这种转换才有效,对 SAM 适配器和 SAM 构造函数都适用(更多细节请参阅 SAM 转换文档)。

下面是一个例子:

1
2
3
4
5
6
public @interface SamWithReceiver {}

@SamWithReceiver
public interface TaskRunner {
    void run(Task task);
}
1
2
3
4
5
6
7
8
9
fun test(context: TaskContext) {
    val runner = TaskRunner {
        // 这里 'this' 是 'Task' 的实例

        println("$name is started")
        context.executeTask(this)
        println("$name is finished")
    }
}

Gradle

用法与 all-open 和 no-arg 相同,区别在于 sam-with-receiver 没有任何内置预设,你需要指定自己的特殊处理注解列表。

Kotlin

1
2
3
plugins {
    kotlin("plugin.sam.with.receiver") version "2.4.20"
}

Groovy

1
2
3
plugins {
    id "org.jetbrains.kotlin.plugin.sam.with.receiver" version "2.4.20"
}

然后指定 SAM-with-receiver 注解列表:

1
2
3
samWithReceiver {
    annotation("com.my.SamWithReceiver")
}

Maven

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<plugin>
    <artifactId>kotlin-maven-plugin</artifactId>
    <groupId>org.jetbrains.kotlin</groupId>
    <version>${kotlin.version}</version>

    <configuration>
        <compilerPlugins>
            <plugin>sam-with-receiver</plugin>
        </compilerPlugins>

        <pluginOptions>
            <option>
                sam-with-receiver:annotation=com.my.SamWithReceiver
            </option>
        </pluginOptions>
    </configuration>

    <dependencies>
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-maven-sam-with-receiver</artifactId>
            <version>${kotlin.version}</version>
        </dependency>
    </dependencies>
</plugin>

命令行编译器

把插件 JAR 文件添加到编译器插件 classpath,并指定 sam-with-receiver 注解列表:

1
2
-Xplugin=$KOTLIN_HOME/lib/sam-with-receiver-compiler-plugin.jar
-P plugin:org.jetbrains.kotlin.samWithReceiver:annotation=com.my.SamWithReceiver