简体   繁体   English

如果我们将 Optional.of 方法设为私有,并且只允许 Java 中的 Optional.ofNullable 会怎样; 除了向后兼容会不会有什么问题?

[英]What if we make the Optional.of method private, and only allow Optional.ofNullable in Java; would there be any problem except backwards-compatibility?

This question has to be updated because it is marked as duplicated, but all the linked questions are not completely matching what is tried to be asked:这个问题必须更新,因为它被标记为重复,但所有链接的问题并不完全匹配试图提出的问题:

Is there a reason, that Optional.of(aNullableVar) is required, as Optional.ofNullable(aNullableVar) checks for null pointer inner the method?是否有一个原因,即Optional.of(aNullableVar)是必需的,因为Optional.ofNullable(aNullableVar)检查方法内部的空指针?

As what Savior answered , a purpose may be like a guard clause:正如Savior 回答的那样,目的可能就像一个保护条款:

Object object = getObject();
Optional.of(object);
System.out.println(object.toString());

It's equivalent to:它相当于:

Object object = getObject();
Objects.requireNonNull(object);
System.out.println(object.toString());

and

Object object = getObject();
if (object == null) {
    throw new NullPointerException();
}
System.out.println(object.toString());

Optional.of in Java 8: Java 8 中的 Optional.of :

public static <T> Optional<T> of(T value) {
    return new Optional<>(value);
}

Optional.ofNullable in Java 8: Java 8 中的 Optional.ofNullable:

public static <T> Optional<T> ofNullable(T value) {
    return value == null ? empty() : of(value);
}

Optional.of serves a double purpose of constructing an Optional with the given non- null value, but also failing fast if the value is actually null . Optional.of具有双重目的,即使用给定的非null值构造一个Optional ,但如果该值实际上是null ,也会快速失败

It's analogous to doing这类似于做

Objects.requireNonNull(value);
// and then using value

So nothing would really break, you'd just find out much later that you used a null value to create that Optional when you shouldn't have.所以没有什么会真正中断,你会在很久以后发现你使用了一个null值来创建你不应该使用的Optional

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM