Edit Page

SAM-with-receiver 编译器插件

最终更新: 2024/03/21

sam-with-receiver 编译器插件可以将带注解的 Java "single abstract method" (SAM) 接口方法的第一个参数变成 Kotlin 中的接受者. 只有在使用 SAM 适配器(Adapter) 和 SAM 构造器(Constructor), 将 Kotlin Lambda 表达式作为 SAM 接口传递时, 这个变换才有效. (详情请参见 SAM 变换文档).

下面是一段示例:

public @interface SamWithReceiver {}

@SamWithReceiver
public interface TaskRunner {
    void run(Task task);
}
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 没有任何预定义, 因此你需要自己指定需要特别处理的注解.

plugins {
    kotlin("plugin.sam.with.receiver") version "1.9.23"
}
plugins {
    id "org.jetbrains.kotlin.plugin.sam.with.receiver" version "1.9.23"
}

然后指定需要特别处理的 SAM-with-receiver 注解:

samWithReceiver {
    annotation("com.my.SamWithReceiver")
}

Maven

<plugin>
    <artifactId>kotlin-maven-plugin</artifactId>
    <groupId>org.jetbrains.kotlin</groupId>
    <version>1.9.23</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>1.9.23</version>
        </dependency>
    </dependencies>
</plugin>

命令行编译器

将插件的 JAR 文件添加到编译器的插件 classpath, 并指定需要处理的 sam-with-receiver 注解:

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