6 comments

Thanks for the reply. I have tried the ShortenReferences.DEFAULT.process() method, but that doesn't work.

My scenario is shorten a function's return value's FQN type. It looks something like:

" fun foo(): Observable<com.my.pkg.SomeType>". my type is inside a class-template(< >). I am afraid ShortenReferences does not deal that case, Maybe just shorten on a variable's type declaration.  Now I have to add import for my type manually:(

0

David Smith hi! Can you please share how did you use ShortenReferences class? It should work in the case that you've described

0

Hi Roman, here is my code:

val newFunc = psiFactory.createFunction(
"@GET(\"/wb/api/block/shelve\")\n" +
" fun get$pojoName(@QueryMap argMap: Map<String, Any>): Observable<$packageName.$pojoName>")

WriteCommandAction.runWriteCommandAction(e.project) {
lastFunc.addSiblingAfter(newFunc)
// wapFile.addPojoImport(psiFactory)

val psiManager = PsiManager.getInstance(project)
val wapFile = psiManager
.findFile(
VfsUtil.findFileByIoFile(
File(project.basePath.plus(WEB_API_PATH)),
true
)!!
)!! as KtFile

val wapClass = wapFile.children.filterIsInstance<KtClass>()[0]
val lastFunc = wapClass.declarations
.filterIsInstance<KtNamedFunction>()
.last()

val typeRefNode = lastFunc.node.findChildByType(KtNodeTypes.TYPE_REFERENCE)!!
.findChildByType(KtNodeTypes.USER_TYPE)!!
.findChildByType(KtNodeTypes.TYPE_ARGUMENT_LIST)!!
.findChildByType(KtNodeTypes.TYPE_PROJECTION)!!
.findChildByType(KtNodeTypes.TYPE_REFERENCE)!!
println("typeRefNode's text is: ${typeRefNode.text}") // com.my.pkg.webapi.response.RepoDetail
ShortenReferences.DEFAULT.process(KtTypeReference(typeRefNode))
}

I know the target to shorten is a KtTypeRef, and I can't find a way to find it out, so i use ASTNode's finding way, at last i construct a KtTypeRef object. 

0
ShortenReferences.DEFAULT.process(KtTypeReference(typeRefNode))

This will most probably not work

You need to have your PSI in the place where it can be actually shortened - a full file with list of imports, for example. You create `KtTypeReference` in the air, it is not attached to the real file, so it will not be shortened

What I suggest doing is the following: insert FQN type to the original file, so it can be successfully resolved, and after that run `ShortenReferences.DEFAULT.process` on it. Could you give it a try?

0

Thanks for the suggestion. I took a light try: first time append new code to the file, then run second time, this time didn't write any, and find the PSI previously added, then use ShortenReferences.DEFAULT.process, but doesn't work as expected. Now I am working on other stuff. So newbie manually add imports as a workaround. 

0

Please sign in to leave a comment.