gpt4 book ai didi

java - 无法理解 "Null type mismatch"

转载 作者:行者123 更新时间:2023-12-02 05:17:19 24 4
gpt4 key购买 nike

任何人都可以解释为什么循环中的打印语句会产生错误(空类型不匹配:需要“@NonNull SortedSet”,但提供的值指定为@Nullable)而循环外的值则不然。

我预计这是一个 Java 错误。是否有不涉及禁用空检查的解决方法? (该代码没有任何意义,它只是重现了问题)。

public class Test
{
static void print(PrintStream ps, @Nullable SortedSet<IState> states)
{
if (states != null)
{
ps.print(Utility.getElt(0, states));
}
for (int q = 0; q < 1; q++)
{
if (states != null)
{
ps.print(Utility.getElt(0, states));
}
}
}
}

Utility.getElt 具有以下签名:

public static <@Nullable T> T getElt(int idx, @NonNull SortedSet<T> set);

如果我删除 getElt 的 @NonNull 注释,问题就会消失,但我真的想要在这里有一个非空“集”。

事实上,注释取自 org.eclipse.jdt.annotation。

最佳答案

根据documentation ,在零分析期间,

Depending on this option, the compiler will issue either an error or a warning whenever one of the following situations is detected:

A method declared with a nonnull annotation returns a nullable expression.

A nullable expression is passed as an argument in a method call where the corresponding parameter of the called method is declared with a nonnull annotation.

A nullable expression is assigned to a local variable that is declared with a nonnull annotation.

A method that overrides an inherited method declared with a nonnull annotation tries to relax that contract by specifying a nullable annotation (prohibition of contravariant return).

A method that overrides an inherited method which has a nullable declaration for at least one of its parameters, tries to tighten that null contract by specifying a nonnull annotation for its corresponding parameter (prohibition of covariant parameters).

在上面的表达式中,如果静态已知其计算结果为 null,或者使用可为 null 注释声明它,则该表达式被视为可为 null。

(强调已添加)。就您而言,您正试图通过 Nullable值为 NonNull参数。

关于java - 无法理解 "Null type mismatch",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26817148/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com