What is the correct way to modify a KtFunction body? Follow
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 🙏
Please sign in to leave a comment.
Try this:
These code work for me.
Huh. But is this the correct way? This part of the docs say to never manually add newlines.
For this case it's considered OK to use psiFactory.createNewLine(), in fact there are plenty of such usages in Kotlin plugin itself.
Great—thank you both!