SAM-with-receiver 컴파일러 플러그인
SAM-with-receiver 컴파일러 플러그인
어노테이션을 단 Java 단일 추상 메서드(SAM) 인터페이스의 첫 번째 파라미터를 Kotlin에서 리시버로 만들어 주는 sam-with-receiver 컴파일러 플러그인을 소개할게요.
본문
sam-with-receiver 컴파일러 플러그인은 어노테이션을 단 Java "단일 추상 메서드"(single abstract method, SAM) 인터페이스 메서드의 첫 번째 파라미터를 Kotlin에서 리시버로 만들어 줘요. 이 변환은 SAM 인터페이스가 Kotlin 람다로 전달될 때만 동작하며, SAM 어댑터와 SAM 생성자 양쪽에 모두 적용돼요. 자세한 내용은 SAM 변환 문서를 참고하세요.
다음은 그 예시예요.
public @interface SamWithReceiver {}
@SamWithReceiver
public interface TaskRunner {
void run(Task task);
}
fun test(context: TaskContext) {
val runner = TaskRunner {
// Here 'this' is an instance of '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 "2.4.20"
}
plugins {
id "org.jetbrains.kotlin.plugin.sam.with.receiver" version "2.4.20"
}
그다음에는 SAM-with-receiver 어노테이션 목록을 지정해 주세요.
samWithReceiver {
annotation("com.my.SamWithReceiver")
}
Maven
<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 파일을 컴파일러 플러그인 클래스패스에 추가하고 sam-with-receiver 어노테이션 목록을 지정해 주세요.
-Xplugin=$KOTLIN_HOME/lib/sam-with-receiver-compiler-plugin.jar
-P plugin:org.jetbrains.kotlin.samWithReceiver:annotation=com.my.SamWithReceiver