如何解决自定义 lint 规则中 context.report 的重载解析歧义?

How to resolve Overload resolution ambiguity for context.report within custom lint rules?

我今天开始学习如何制定一些基本的 lint 规则,尝试为变量创建 lint 规则,以检查其名称的长度。

@Suppress("UnstableApiUsage")
class VariableLengthDetector : Detector(), Detector.UastScanner {

override fun getApplicableUastTypes() = listOf(UVariable::class.java)

override fun createUastHandler(context: JavaContext) =
    VariableLengthHandler(context)


class VariableLengthHandler(private val context: JavaContext) :
    UElementHandler() {

    private val variableMinimumLength = 3

    override fun visitVariable(node: UVariable) {

        node.name?.let {
            if (it.length < variableMinimumLength) {
                context.report(
                    issue = variableLengthIssue,
                    scope = node,
                    location = context.getNameLocation(node),
                    message = "this variable can be better named"
                )
            }
        }
    }
}

}

此代码无法编译,因为此处导致的重载歧义:

context.report(issue = variableLengthIssue,
               scope = node,
               location = context.getNameLocation(node),
               message = "this variable can be better named")

据我所知,这是因为 context.report 的重载可以是

public final fun report(issue: Issue, scope: PsiElement?,...

也可以是

public final fun report(issue: Issue, scope: UElement?,...

但我不确定如何使用我拥有的 Uvariable 元素来定义这些?

如何解决此重载歧义?

您可以将其转换为 UElement

context.report(
    issue = variableLengthIssue,
    scope = node as UElement,
    location = context.getNameLocation(node),
    message = "this variable can be better named"
)