向可选项提供空列表?

huangapple go评论104阅读模式
英文:

Providing an Empty List to an Optional?

问题

  1. 假设我有以下布局
  2. ```java
  3. public void caller(@NonNull List<Integer> param){
  4. // param可以是空的,但不能为null,它不可为空
  5. if(!param.isEmpty()) function(Optional.of(param));
  6. // 如果param是空的,那就不要调用"function"
  7. }
  8. public void function(Optional<List<Integer>> someParam){
  9. someParam.ifPresent(...);
  10. }

问题是:基于空列表创建Optional是否是正确的用法?我感到困惑的是,我们是否应该提供一个Optional,无论caller中的param是否为空,因为它不为null,但我想知道这是否是正确的用法?

  1. <details>
  2. <summary>英文:</summary>
  3. Suppose I have this layout:

public void caller(@NonNull List<Integer> param){
// param COULD BE EMPTY, but it CANNOT be NULL, its not nullable
if(!param.isEmpty()) function(Optional.of(param));
// If param is empty then just dont call "function"
}

public void function(Optional<List<Integer>> someParam){
someParam.ifPresent(...);
}

  1. Here is the question: Is not creating an `Optional` based on an empty list correct usage? The confusion I am having is whether we should be providing an Optional regardless if `param` in `caller` is empty or not because it is not null, but I am wondering if this is the right usage?
  2. </details>
  3. # 答案1
  4. **得分**: 3
  5. 1. `someParam.ifPresent(...);` `ifPresent` 方法的主体总是会被调用,因为总是会有一个元素,即使它是一个空列表(你正在检查非空性 `@NonNull List&lt;Integer&gt; param`)。
  6. 2. 你正在使用 `Optional.of` 而不是 `Optional.ofNullable`,因此始终会有一个非空元素。
  7. 3. 将列表包装在 `Optional` 中没有太多意义,为什么不传递一个空列表并且不处理任何元素呢?
  8. 4. `if(!param.isEmpty())` 是多余的,因为你知道列表中有元素,就像第3点所述,为什么不直接传递列表进行处理呢?
  9. **简而言之**:你将空列表与 `null` 混淆了,在任何集合中包装 `Optional` 都没有太多意义。
  10. <details>
  11. <summary>英文:</summary>
  12. 1. `someParam.ifPresent(...);` the body of `ifPresent` is always invoked, because there always is an element, even if it&#39;s an empty list (you&#39;re checking for nullity `@NonNull List&lt;Integer&gt; param`).
  13. 2. You&#39;re using `Optional.of` instead of `Optional.ofNullable`, so there is always going to be a non-null element.
  14. 3. Wrapping list in `Optional` does not make much sense, why not passing an empty list and not processing any elements?
  15. 4. `if(!param.isEmpty())` is redundant, because you know there are elements in the list, as stated in 3. why not passing the list for processing?
  16. **tl;dr**: You&#39;re mixing an empty list with `null`, wrapping any collection in `Optional` does not make much sense.
  17. </details>

huangapple
  • 本文由 发表于 2020年3月16日 21:56:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/60707325.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定