Android源代码表明findViewById
可以返回null:
@Nullable
public final <T extends View> T findViewById(@IdRes int id) {
if (id == NO_ID) {
return null;
}
return findViewTraversal(id);
}
但是当从Kotlin调用它时,编译器在使用这种方式时不会抱怨可空性:
private lateinit var swipeRefreshLayout: SwipeRefreshLayout
...
swipeRefreshLayout = view.findViewById(R.id.swiperefresh)
我可以猜测,这个Nullable
注释来自android pacakge,还有其他Nullable
注释,Kotlin确实很清楚。是Kotlin / IDE相关问题还是Android团队应该对此做些什么?
findViewById
正在使用泛型。我们明确提供它应该返回的类型。如果我们重写init行,编译器会抱怨可空性。
swipeRefreshLayout = view.findViewById<SwipeRefreshLayout?>(R.id.swiperefresh)