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?
Asked
Active
Viewed 2,101 times
20

Bradley Campbell
- 9,298
- 6
- 37
- 47
-
How exactly are you compiling your application? – yole Feb 02 '16 at 08:45
-
Using the kotlin-android gradle plugin. Sorry, that's a pretty important detail. – Bradley Campbell Feb 02 '16 at 09:56
-
Can you post a sample project that demonstrates the issue? – miensol Feb 02 '16 at 17:57
-
1Yes. I just added a branch to my project with the broken code: https://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 Feb 02 '16 at 19:03
-
Is there any similar issue in the KEEP/kotlin tracking system? – wnc_21 Apr 28 '17 at 09:14
2 Answers
2
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)

Alexander Blinov
- 393
- 3
- 13
0
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'
}

Fabian Zeindl
- 5,860
- 8
- 54
- 78