Search code examples
androidandroid-studiokotlinintellij-ideaannotations

How to let IntelliJ show error when value is not met requirement [Kotlin]


This is an simplified example of what I try to do but still failed

        class Definition {
            @Target(AnnotationTarget.TYPE, AnnotationTarget.VALUE_PARAMETER)
            @IntDef(View.VISIBLE, View.INVISIBLE, View.GONE)
//only 0,4,8 are allowed
            @Retention(AnnotationRetention.SOURCE)
            annotation class Visibility
        }
    
    fun isVisibleView(@Definition.Visibility visibility: Int, viewList: ArrayList<View>, ) {
            for (view in viewList) {
                view.visibility = visibility
            }
        }
    
    //I want the ide to SHOW ERROR here since 2 is not in 0,4,8 (show before compile)
     isVisibleView(2, visibleItems)

I think this question is about IDE config or Kotlin syntax


Solution

  • In short Enum is enough.

    IntDef is android specific so you'd have to find an Android rule for IntelliJ to analyze those annotations.

    Even you can make it work it only on java not Kotlin. It seems like the warning will be generated by lint but only if you write the annotation in Java, not Kotlin

    As state in this issue https://youtrack.jetbrains.com/issue/KTIJ-18693

    https://developer.android.com/studio/write/annotations?fbclid=IwAR2duPFqsMx1VPDlK0nyt8-mAKJyLw_WAjY5GQMIHH__-FMpRV9SNJpqY6k

    Credit: Anton Malinsky