[Project Structure Interface] Unexpected behavior for KtClassBody.add() method

Answered

Hello everyone!

I'm trying to add a KtProperty into KtClassBody

I obtain a KtClassBody like this:

val ktClass = ktPsiFactory.createClass("class Test {}")
val ktClassBody = ktClass.getChildOfType<KtClassBody>()

Then, I create a KtProperty and try to add it into KtClassBody:

val ktProperty = ktPsiFactory.createProperty("private val intValue: Int = 0")
ktClassBody?.add(ktProperty)

Finally, I add the KtFile that containing the ktClass in PsiDirectory and check the generation result.

 

But I find the generation result is incorrectly:

class Test {}
private val intValue: Int = 0

What's wrong with my code and how can I solve it? Thank you! Have a happy day :)

1 comment
Comment actions Permalink

Finally I find that 

val ktProperty = ktPsiFactory.createProperty("private val intValue: Int = 0")
ktClassBody?.addBefore(ktProperty, ktClassBody.rBrace)

can solve my problem ...

0

Please sign in to leave a comment.