What's the methed call to Resolve a Kotlin reference

The following code works for Java files:
val node: ASTNode
....
val referencedFieldElement = node.psi.reference!!.resolve()

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 ?

1

I have exactly the same question

0
Avatar
Permanently deleted user

I have a plugin written for Java which works great but it doesn't support the Kotlin files because I can't find a way to resolve the reference.
Any idea are appreciated.

1

What I've tried:

SyntaxTraverser
.psiTraverser(ktFile)
.traverse()
.transform(ReferenceProvidersRegistry::getReferencesFromProviders)
.filter(Objects::nonNull)
.filter(it -> it.length > 0)
.toList()

The code above returns an empty array, while the ktFile is a valid kotlin file and can be compiled within my mixed Java-Kotlin project (all necessary "PsiFile"s are included in the "Project" of "ktFile").

SyntaxTraverser
.psiTraverser(ktFile)
.traverse()
.transform(PsiElement::getReference)
.filter(Objects::nonNull)
.toList()

This code returns an empty list.

 

But at the same time, all Java files are in the same project and all of them resolves to correct references.

 

How can I resolve Kotlin references?

0

First of all, you're only looking for references on the leaf nodes. It's not the case that only leaf nodes can contain references. If you don't find any references on a leaf node, you need to use `PsiElement.getParent()` to look for references in its parent nodes.

Second, an element can contain multiple references (and Kotlin elements do). Instead of calling `getReference().resolve()`, you need to call `getReferences()` and iterate over them until you find one which is resolved to a non-null element.

0
Avatar
Permanently deleted user

I will try that. Do you know by any chance the sources of a plugin which illustrates this usage ?

0

I don't, sorry.

0

@yole I tried this, according to you:

 

SyntaxTraverser
.psiTraverser(ktMethod.getContainingKtFile())
.traverse()
.transform(PsiElement::getReferences)
.filter(it -> it.length > 0)
.toList()

And I get an empty list...

0

请先登录再写评论。