7

I would like to restrict on which constant value extension function can be called. For example function like:

@IdRes
fun <T : View> Int.find() = findViewById<T>(this)

If this was called on real id, it's fine:

R.id.someView.find<TextView>() // ok

But this should make compilation error:

42.find<TextView>() // should be compile error

Is annotating extension receiver supported in Kotlin?

xinaiz
  • 7,744
  • 6
  • 34
  • 78

1 Answers1

12

As described in the documentation, you can use the following syntax:

fun @receiver:IdRes <T : View> Int.find() = ...

However, note that the Kotlin compiler is not aware of the semantics of the Android annotations, so their incorrect use is never a compilation error; it's at best a failed lint check.

yole
  • 92,896
  • 20
  • 260
  • 197
  • This doesn't highlight the call when `R.color.colorPrimary.find()` is used – xinaiz Jul 04 '18 at 07:35
  • 1
    Most likely the lint checks don't handle annotations on the receiver. You can file an issue in the Android issue tracker. – yole Jul 04 '18 at 08:13