为什么Android Studio具有此@Nullable东西? [英] Why Android Studio has this @Nullable thing?

查看:96
本文介绍了为什么Android Studio具有此@Nullable东西?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Android Studio向我展示的这个奇怪的东西有点好奇.弹出类似工具提示的内容时,我将使用 addView 方法:

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:

由于参数上的 @Nullable 注释,我感到很困惑. View 可以为null,因为它是一种引用类型.但是,为什么要使用显式的 @Nullable 注释?

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?

当我进入 addView 方法的定义时,看不到任何注释!那我就更困惑了.

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

所以我想问一个问题,为什么Android Studio会有这种奇怪的事情.

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

推荐答案

View 可以为null,因为它是引用类型.但是为什么要明确 @Nullable 批注?

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

从技术意义上讲,是的,View是参考,因此 null 是值之一.同样,重载之一中的 width height 参数的类型为 int ,因此从技术上讲,您可以传递 0 ,例如 2147483647 -1 值作为高度,但可能没有任何意义.以同样的方式,将 null 作为值传递,无论在语法上是有效的,都可能有意义,也可能没有意义.某些函数在传递 null 值时会抛出 NullPointerException . @Nullable 注释表示 null 是可接受的值,函数将处理该值:

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:

可空:

表示参数,字段或方法的返回值可以为null.

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

装饰方法调用参数时,表示参数可以合法为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.

在装饰方法时,这表示该方法可能合法返回null.

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

这是一个标记注释,它没有特定的属性.

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

这篇关于为什么Android Studio具有此@Nullable东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆