What is the correct way to modify a KtFunction body?

Answered

I have a function like this:

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val view = LayoutInflater.from(context).inflate(R.layout.xyz, null, false)

... // rest of code
}

All I'd like to do is add a line of code after the `view` property, like so:

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val view = LayoutInflater.from(context).inflate(R.layout.xyz, null, false)

binding = MyViewBinding.bind(view) // <-- i want to add this line

... // rest of code
}

To achieve this, I wrote the following code:

private fun KtFunction.processOnCreateDialog(psiFactory: KtPsiFactory, bindingVariableName: String, bindingClassName: String) {
val viewInflateProperty = bodyExpression!!.children
.find { it is KtProperty && it.text.contains("inflate") } as KtProperty?

if (viewInflateProperty != null) {
val bindingInstantiateExpression = psiFactory.createExpression(
"$bindingVariableName = $bindingClassName.bind(${viewInflateProperty.name})")
bodyExpression!!.addAfter(bindingInstantiateExpression, viewInflateProperty)
}
}

 

However, that results in my expression generating on the same line as the view property which results in a compilation error. I.e:

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val view = LayoutInflater.from(context).inflate(R.layout.xyz, null, false)binding = DialogFeatureFlagOverrideBinding.bind(view)

Clearly I am misunderstanding how to do this. The documentation says I shouldn't add newlines manually either. So I'm a bit stuck and can't figure out how to proceed. Any help would be greatly appreciated 🙏

4 comments
Comment actions Permalink

Try this:

private fun KtFunction.processOnCreateDialog(psiFactory: KtPsiFactory, bindingVariableName: String, bindingClassName: String) {
...
if (viewInflateProperty != null) {
...
bodyExpression?.addBefore(psiFactory.createNewLine(), bodyExpression?.rBrace) // add a new line before }
bodyExpression?.addBefore(bindingInstantiateExpression, bodyExpression?.rBrace) // add code before }
}
}

These code work for me.

0
Comment actions Permalink

Huh. But is this the correct way? This part of the docs say to never manually add newlines. 

0
Comment actions Permalink

For this case it's considered OK to use psiFactory.createNewLine(), in fact there are plenty of such usages in Kotlin plugin itself.

0
Comment actions Permalink

Great—thank you both!

0

Please sign in to leave a comment.