8

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?

1 Answer 1

14

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This doesn't highlight the call when R.color.colorPrimary.find() is used
Most likely the lint checks don't handle annotations on the receiver. You can file an issue in the Android issue tracker.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.