20
votes

I have a java annotation processor which generates a bunch of java files during compilation. I'd like to make the generated classes nicer to use in kotlin by adding extension methods. I've been told on the kotlin forums that something I could try would be to write a kotlin file that contains my extension functions. I've tried this, I used the Filer object to create this file outputting it to the StandardLocations.SOURCE_OUTPUT directory. Intellij can see my generated class, and I can use the extension functions as intended, but the app won't compile because the compiler can't find the new kotlin file. Is there any way I can write a new kotlin file that'll get picked up by the kotlin compiler?

2
How exactly are you compiling your application?yole
Using the kotlin-android gradle plugin. Sorry, that's a pretty important detail.Bradley Campbell
Can you post a sample project that demonstrates the issue?miensol
Yes. I just added a branch to my project with the broken code: github.com/grandstaish/paperparcel/tree/kotlin-extensions. Just open the source in Android Studio or Intellij and build the entire project. The kotlin-example app will fail to build.Bradley Campbell
Is there any similar issue in the KEEP/kotlin tracking system?wnc_21

2 Answers

2
votes

For kapt you can get source folder via.

Map<String, String> options = processingEnv.getOptions();
                String generatedPath = options.get("kapt.kotlin.generated");

String path = generatedPath
                    .replaceAll("(.*)tmp(/kapt/debug/)kotlinGenerated",
                            "$1generated/source$2");

Unfortunately it doesn't work for kapt2 (see issue KT-14070)

You also can create .kt files via resource writer

Writer w = processingEnv.getFiler().createResource(SOURCE_OUTPUT, "package_name", "Sample.kt")

But for now you need to invoke compiler twice cause compileDebugKotlin task runs before invoking javax annotation processor by compileDebugJavaWithJavac task)

0
votes

Output your files (with proper package names) into a directory like src/build/generated-src/kotlin/your/package/File.kt

and add this to your build.gradle:

sourceSets {
    main.java.srcDirs += 'build/generated-src/kotlin'
}