今天,我开始学习如何制定一些基本的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元素来定义它们?
如何解决这种过载歧义?
答案 0 :(得分:1)
您可以将其投射为UElement
。
context.report(
issue = variableLengthIssue,
scope = node as UElement,
location = context.getNameLocation(node),
message = "this variable can be better named"
)