Skip to content

SAM-with-receiver 編譯器外掛程式 ​

sam-with-receiver 編譯器外掛程式能讓帶有指定註解的 Java「單一抽象方法」(SAM) 介面方法的第一個參數,在 Kotlin 中成為接收者 (receiver)。此轉換僅在 SAM 介面作為 Kotlin Lambda 運算式傳遞時有效,同時適用於 SAM 適配器與 SAM 建構函式(詳情請參閱 SAM 轉換文件)。

以下為範例:

java
public @interface SamWithReceiver {}

@SamWithReceiver
public interface TaskRunner {
    void run(Task task);
}
kotlin
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
plugins {
    kotlin("plugin.sam.with.receiver") version "2.4.21"
}
groovy
plugins {
    id "org.jetbrains.kotlin.plugin.sam.with.receiver" version "2.4.21"
}

接著指定 SAM-with-receiver 註解清單:

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

Maven ​

xml
<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 註解清單:

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