mardi 26 mai 2020

Retrieve Kotlin Property type from Kotlin psi API?

I'm trying to create new rule for detekt project. To do this I have to know exact type of Kotlin property. For example, val x: Int has type Int.

Unfortunately, for property of type private val a = 3 I receive the following:

  1. property.typeReference is null
  2. property.typeParameters is empty
  3. property.typeConstraints is empty
  4. property.typeParameterList is empty
  5. property.text is private val a = 3
  6. property.node.children().joinToString() has object notation of previous item
  7. property.delegate is null
  8. property.getType(bindingContext) is null (the property bindingContext is part of KtTreeVisitorVoid used

Question: how can I get name of type (or, what is better, object KClass) to compare the actual property type with Boolean class type? (e.g. I just need to get if property boolean of not)

Code:

    override fun visitProperty(property: org.jetbrains.kotlin.psi.KtProperty) {
        val type: String = ??? //property.typeReference?.text - doesn't work

        if(property.identifierName().startsWith("is") && type != "Boolean") {
            report(CodeSmell(
                issue,
                Entity.from(property),
                message = "Non-boolean properties shouldn't start with 'is' prefix. Actual type: $type")
            )
        }
    }




Aucun commentaire:

Enregistrer un commentaire