11

I'm writing an Intellij plugin in Kotlin for Java and Kotlin files. The following code works for Java files:

val node: ASTNode
....
val referencedFieldElement = node.psi.reference!!.resolve()

But it doesn't work for Kotlin files because there is no resolve() method call and node.psi.reference returns null.

How do you resolve a Kotlin reference ?

Also I have a PsiElement Kotlin reference. How can I resolve it's value ?

Here is some code:

class KotlinFoldingBuilder : FoldingBuilderEx() {

    override fun buildFoldRegions(root: PsiElement, document: Document, quick: Boolean): Array<FoldingDescriptor> {
        ....
    }

    override fun getPlaceholderText(node: ASTNode): String? {
        val referencedFieldElement = node.psi.reference!!.resolve()
        return referencedFieldElement
    }

    override fun isCollapsedByDefault(node: ASTNode): Boolean {
        return true
    }
}

node.psi.reference!!.resolve() works for Java file but for Kotlin files node.psi.reference returns null.

A potential answer to this question can be found here https://intellij-support.jetbrains.com/hc/en-us/community/posts/115000795610-What-s-the-methed-call-to-Resolve-a-Kotlin-reference

vovahost
  • 34,185
  • 17
  • 113
  • 116
  • 4
    On which node are you calling this? There are most definitely nodes in the Kotlin PSI that do have references, and those references can be resolved using the regular resolve() method. – yole Jan 05 '18 at 11:10
  • @yole I've added some more code and explanation. Please see the updated question. I tried calling reference on everything. It's always null. Maybe there is some different way to get the referenced value in Kotlin ? I can't even find an example. – vovahost Jan 05 '18 at 11:18
  • 1
    Look, not all PsiElements have a reference! Assume you have a PsiElement that represents a simple number that this will certainly not have a reference connected to it. Simply calling `node.psi.reference!!` is evil. Check if the PsiElement actually has a reference and if yes, you might be able to resolve it. – halirutan Jan 07 '18 at 23:20
  • I get what you're suggesting but I tried to call the resolve on a KtDotReference which is a static reference to a field (Ex: Math.PI) and calling reference() returns null. I also tried calling it on some different Kotlin reference types and all of them return null or some strange result. It's not straightforward like the Java ones. – vovahost Jan 08 '18 at 10:01

0 Answers0