Konfigure KotlinCompile taks from my plugin only when Kotlin plugins is initialized

I would like to configure Kotlions’s KotlinCompile class, but in a lazy way, only when this plugin is used by the project. So I have an only compile-time dependency on Kotlin plugin.

And then I’m trying do this:

project.tasks.matching { it::class.simpleName?.contains("KotlinCompile") ?: false}.all {
 ...
}

And even

project.plugins.matching { it::class.simpleName?.contains("KotlinAndroidPlugin") ?: false }.all {
   project.tasks.matching { it::class.simpleName?.contains("KotlinCompile") ?: false}.all {
     ...
   }
}

So I’m sure that Kotlin plugin was initialized in the time when my callback is called.
If there is no Kotlin it is not called.
But still, inside of inner lambda, I got java.lang.NoClassDefFoundError every time I tried to touch KotlinCompile class :disappointed:
I don’t understand how Gradle can add KotlinCompile task without having it loaded by classloader.

Until now we was using old good apply way, which has one big advantage, that all classes of all plugins are on classpath in the time of plugin initialisation.

So I was able do just this

project.tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
  ....
}

And it works great. But now with plugins {} this way doesn’t works.

It looks that Gradle is using a different classloader for every plugin when I’m using just plugins {} without adding kotlin plugin on classpath. So there are probably just two solution add Kotlin plugin to classpath, but then you can specify version inside of plugins block or using just reflection. I did not found a way how to force part of my code to by loaded by proper class loader which has to both plugins. Maybe it is somehow possible.

The issue is that I was using buildSrc and it really using a different classloader, so then nothing from buildSrc can directly cooperate with any plugin loaded outside of buildSrc.

I used included build instead of buildSrc and the problem is gone.