Zac Sweers
08/09/2023, 8:15 PMEnum.entries
in Kotlin 1.9, here's one I wrote. You can make it an inspection too
Template
$Before$.$Method$()
For $Before$
, add a script modifier with this script. This was the only way I could actually tell if a class was an enum or not, no combination of type hierarchy checks or regexes would work.
import com.intellij.psi.*;
import org.jetbrains.kotlin.psi.*;
public boolean isReferencedClassEnum(KtDotQualifiedExpression expression) {
KtExpression receiverExpression = expression.getReceiverExpression();
if (receiverExpression instanceof KtNameReferenceExpression) {
PsiElement resolved = ((KtNameReferenceExpression) receiverExpression).getReference().resolve();
if (resolved instanceof KtClass) {
return ((KtClass) resolved).isEnum();
}
}
return false;
}
if (__context__ instanceof KtDotQualifiedExpression) {
isReferencedClassEnum((KtDotQualifiedExpression) __context__)
} else {
false
}
Here's a pasteable template you can import from clipboard
<replaceConfiguration name="Replace Enum.values() with Enum.entries" text="$Before$.$Method$()" recursive="false" type="Kotlin" pattern_context="default" reformatAccordingToStyle="false" shortenFQN="false" replacement="$Before$.entries" case_sensitive="true">
<constraint name="__context__" within="" contains="" />
<constraint name="Before" script=""import com.intellij.psi.*; import org.jetbrains.kotlin.psi.*; public boolean isReferencedClassEnum(KtDotQualifiedExpression expression) { KtExpression receiverExpression = expression.getReceiverExpression(); if (receiverExpression instanceof KtNameReferenceExpression) { PsiElement resolved = ((KtNameReferenceExpression) receiverExpression).getReference().resolve(); if (resolved instanceof KtClass) { return ((KtClass) resolved).isEnum(); } } return false; } if (__context__ instanceof KtDotQualifiedExpression) { isReferencedClassEnum((KtDotQualifiedExpression) __context__) } else { false }"" within="" contains="" />
<constraint name="Method" regexp="values" within="" contains="" />
</replaceConfiguration>
To make it go faster if you're trying to do one big migration, I suggest doing a simple string search for .values()
repo-wide, then run the inspection with the scope of the "Files in last search result"eygraber
08/09/2023, 8:25 PMvalues()
with entries
through Replace in files but YMMVephemient
08/09/2023, 8:25 PMZac Sweers
08/09/2023, 8:26 PMZac Sweers
08/09/2023, 8:26 PMColton Idle
08/10/2023, 2:07 AM