IncorrectOperationException in an intellij plugin for Kotlin

Hi,
I’m trying to extend a plugin for files written in Kotlin. The plugin is supposed to modify Kotlin classes. For this purpose I use methods like

PsiClass.addBefore() PsiClass.addAfter()

I have no problem in getting PsiClass instances, their methods of Kotlin files, but once it comes down to using the above mentioned method, I get the exception

IncorrectOperationException

The plugin handles correctly Java classes, but Kotlin ones are always giving this exception when I use the above methods.

Could somebody give me a hint how to deal with Kotlin classes as well?
Thanks!

You need to get the underlying Kotlin class instance (check if the PsiClass is an instance of KtLightElement, and if it is, access its kotlinOrigin property) and to add the PSI elements (created using KtPsiFactory, not the Java PSI factory) to the returned KtClass.

1 Like

Thanks for your suggestion!
I must be missing something because the editor says

Cannot resolve symbol 'KtLightElement'

If I get it right, this class should be in package

org.jetbrains.kotlin.asJava.classes

but I can not import it since I don’t know its location. Could you, please, tell me where I can get that class from?

You need to add the jar of the Kotlin plugin to the classpath of your IntelliJ IDEA SDK.

1 Like

Thanks! Now it works!

Hi,
I had same problem like @veontomo but I do’t know what is kotlin plugin jar file , any help will be appreciated

when i’m download kotlin-plugin-1.2.31 find kotlin-plugin.jar , what is this?

when i put kotlin-plugin.jar in my project dir ‘libs’, i can use KtLightElement bu find exception
java.lang.ClassCastException: org.jetbrains.kotlin.asJava.classes.KtLightClassImpl cannot be cast to org.jetbrains.kotlin.asJava.classes.KtLightClassImpl: Ljava/lang/ClassCastException;

Please see Dependencies | IntelliJ Platform Plugin SDK for instructions on how to add a plugin dependency correctly.

I just wanted to mention that I am not making use of any of those methods myself. Instead, I wanted to auto generate an OnClick function defined in my layout xml file and it threw the same error.