Kotlin annotate receiver of extension function

*爱你&永不变心* 提交于 2020-06-16 04:46:26

问题


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:


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.



来源:https://stackoverflow.com/questions/51156576/kotlin-annotate-receiver-of-extension-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!