Add new parameter into kotlin data class from IDEA plugin

Answered

Hi!
I want my plugin would be able to insert new parameters in kotlin data classes.
My code now:
```
String paramText = "@MyCustomAnnotation(description = \"some text here\")" + '\n' + "var fieldName: MyFieldClass?";
KtPsiFactory psiFactory = new KtPsiFactory(project);
KtParameter ktParam = dataClass.getPrimaryConstructor().getValueParameterList().addParameter(psiFactory.createParameter(paramText));
dataClass.addBefore(psiFactory.createNewLine(), ktParameter);
```
This code has two problems:

  1. JavaCodeStyleManager.shortenClassReferences(ktParam) does nothing (if I use correct full qualified names for my classes inside paramText), so now I have to add import statements with document::insertString, which doesn't look like a correct way to do it;
  2. I have a message with "anchoreBefore == null || anchorBefore.getTreeParent() == parent" from addBefore method, however, the new line is succesfully created by this code.

So I have several questions:

  • Should I create this parameter in another way?
  • Is there any code style setting for empty lines between parameters in kotlin data classes?
  • Can I optimize imports for kotlin files from my plugin (JavaCodeStyleManager::optimizeImports works only for PsiJavaFiles)
1 comment
Comment actions Permalink

Hi Abaklan88! Sorry for the late response; I hope that the answers will still be relevant.

 

JavaCodeStyleManager.shortenClassReferences(ktParam) does nothing

It is intended behavior; we have our own facility to shorten references in Kotlin called ShortenReferences

You can see how it is used here, for example. It is a part of SpecifyTypeExplicitlyIntention intention, which adds explicit type to the declarations (val a = "" -> val a: String = "", for example)

You can probably just call ShortenReferences.DEFAULT.process(typeRef), where typeRef is a PSI element for your inserted FQN type (it is indeed important to insert FQN)

 

Is there any code style setting for empty lines between parameters in kotlin data classes?

I am afraid not, but I may misunderstand what are you trying to achieve here - can you provide an example?

 

Can I optimize imports for kotlin files from my plugin

Please, try to use LanguageImportStatements.INSTANCE.forFile(ktFile) method. It should return you a collection of the import optimizers, and one of them should be a Kotlin-specific one

0

Please sign in to leave a comment.