带有接收者的 SAM 编译器插件

The sam-with-receiver compiler plugin makes the first parameter of the annotated Java “single abstract method” (SAM) interface method a receiver in Kotlin. This conversion only works when the SAM interface is passed as a Kotlin lambda, both for SAM adapters and SAM constructors (see the SAM conversions documentation for more details).

Here is an example:

  1. public @interface SamWithReceiver {}
  2. @SamWithReceiver
  3. public interface TaskRunner {
  4. void run(Task task);
  5. }
  1. fun test(context: TaskContext) {
  2. val runner = TaskRunner {
  3. // Here 'this' is an instance of 'Task'
  4. println("$name is started")
  5. context.executeTask(this)
  6. println("$name is finished")
  7. }
  8. }

Gradle

The usage is the same to all-open and no-arg, except the fact that sam-with-receiver does not have any built-in presets, and you need to specify your own list of special-treated annotations.

  1. plugins {
  2. id("org.jetbrains.kotlin.plugin.sam.with.receiver") version "$kotlin_version"
  3. }

Then specify the list of SAM-with-receiver annotations:

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

Maven

  1. <plugin>
  2. <artifactId>kotlin-maven-plugin</artifactId>
  3. <groupId>org.jetbrains.kotlin</groupId>
  4. <version>${kotlin.version}</version>
  5. <configuration>
  6. <compilerPlugins>
  7. <plugin>sam-with-receiver</plugin>
  8. </compilerPlugins>
  9. <pluginOptions>
  10. <option>
  11. sam-with-receiver:annotation=com.my.SamWithReceiver
  12. </option>
  13. </pluginOptions>
  14. </configuration>
  15. <dependencies>
  16. <dependency>
  17. <groupId>org.jetbrains.kotlin</groupId>
  18. <artifactId>kotlin-maven-sam-with-receiver</artifactId>
  19. <version>${kotlin.version}</version>
  20. </dependency>
  21. </dependencies>
  22. </plugin>

Command-line compiler

Add the plugin JAR file to the compiler plugin classpath and specify the list of sam-with-receiver annotations:

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