Skip to content

getParentOfTypeAndBranch

inline fun <reified T : PsiElement> PsiElement.getParentOfTypeAndBranch(strict: Boolean = false, noinline branch: T.() -> PsiElement?): T?

Checks the nearest element of type T and returns it if this element lies within the subtree selected by branch. If that candidate's branch does not contain this element, returns null without checking higher ancestors. When strict is false, this element itself is also considered as the candidate.

Example:

Given the PSI for:

if (outerCondition) {
    if (innerCondition) {
        handleInner()
    } else {
        handleFallback()
    }
}

If fallbackCall is the KtCallExpression for handleFallback(), fallbackCall.getParentOfTypeAndBranch<KtIfExpression> { getThen() } returns null. The nearest KtIfExpression is the inner one, and handleFallback() is in its else branch. The search does not continue to the outer if, despite the call also being inside the outer then branch.