Why Android Studio has this @Nullable thing?

有些话、适合烂在心里 提交于 2019-12-13 05:59:13

问题


I am just kind of curious about this weird thing that Android Studio is showing me. I was about to use the addView method when this tool-tip-like thingy pops up:

I am quite confused because of the @Nullable annotations on the parameters. View can be null because it is a reference type. But why an explicit @Nullable annotation?

When I go into the definition of the addView method, I see no annotations! Then I am more confused.

So I want to ask why Android Studio has this weird thingy.


回答1:


View can be null because it is a reference type. But why an explicit @Nullable annotation?

In technical sense, yes, View is reference thus null is one of values. In the same sense, width and height arguments in one of overloads are of type int so technically you could pass 0, 2147483647 or -1 value as height, for example, but it probably wouldn't make any sense. The same way, passing null as a value, however syntactically valid, may or may not make sense. Some functions throw NullPointerException when passed a null value. @Nullable annotation means that null is acceptable value, and function will handle that:

Nullable:

Denotes that a parameter, field or method return value can be null.

When decorating a method call parameter, this denotes that the parameter can legitimately be null and the method will gracefully deal with it. Typically used on optional parameters.

When decorating a method, this denotes the method might legitimately return null.

This is a marker annotation and it has no specific attributes.



来源:https://stackoverflow.com/questions/31936907/why-android-studio-has-this-nullable-thing

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