Search code examples
intellij-pluginintellij-15

Why cannot I get PsiClass from Kotlin but successful in Java


I try to get PsiClass from Kotlin file (the PsiFile instance is KtFile), but aways get null, In Java case is successful.

    PsiFile psiFile = e.getData(CommonDataKeys.PSI_FILE);
    Editor editor = e.getData(CommonDataKeys.EDITOR);

    // null in kotlin
    PsiClass psiClass = getPsiClass(editor, psiFile);

    .....    

    private PsiClass getPsiClass(Editor editor, PsiFile file) {

        int offset = editor.getCaretModel().getOffset();
        PsiElement element = file.findElementAt(offset);

        if (element == null)
            element = file.findElementAt(offset - 1);
        if (element == null) {
            return null;
        } else {
            PsiClass target = (PsiClass) PsiTreeUtil.getParentOfType(element, PsiClass.class);
            if (target == null) {
                element = file.findElementAt(offset - 1);
                if (element == null)
                    return null;
                target = (PsiClass) PsiTreeUtil.getParentOfType(element, PsiClass.class);
            }
            return target instanceof SyntheticElement ? null : target;
        }
    }

Solution

  • PsiClass is used only for java classes. For Kotlin you should use KtClass.