简体   繁体   中英

Android nullable annotation not recognized in Kotlin

Android source code suggests that findViewById can return null:

@Nullable
public final <T extends View> T findViewById(@IdRes int id) {
    if (id == NO_ID) {
        return null;
    }
    return findViewTraversal(id);
}

But when calling it from Kotlin, compiler doesn't complain about nullability when using this way:

private lateinit var swipeRefreshLayout: SwipeRefreshLayout
...
swipeRefreshLayout = view.findViewById(R.id.swiperefresh)

As I can guess, this Nullable annotation is from android pacakge and there are also other Nullable annotations, that Kotlin does recognize well. Is it Kotlin/IDE related issue or should Android team do something about this?

findViewById is using generics. We explicitly provide the type it should return. If we rewrite the init line, compiler would complain about nullability.

swipeRefreshLayout = view.findViewById<SwipeRefreshLayout?>(R.id.swiperefresh)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM