B
B
beduin012019-11-08 16:10:39
Java
beduin01, 2019-11-08 16:10:39

Why is Optional needed and why can't the same actions be performed on null?

I don't think language matters here. I can't figure out why the Optional type was introduced? What prevented everything from being done over null too?

ArrayList<Integer> numbers = new ArrayList<Integer>();
Optional<Integer> min = numbers.stream().min(Integer::compare);
if(min.isPresent()){
             
    System.out.println(min.get());
}

Because null is a pointer and not a class? Why couldn't isPresent be implemented for it?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
K
koperagen, 2019-11-08
@beduin01

You can check the reference for null anyway, without any additional methods and entities. Optional here explicitly says that the result of the method may exist (value) or not exist (null) and does not allow you to get a value without making a choice how to handle the situation with its absence. In addition to the usual get(), there are also getOrElse() methods that allow you to specify a default value, getOrNull().
It can also be convenient to first perform a chain of transformations on Optional using the map() method, and at the end get the value in any convenient way and then work with a "pure" object of the expected type.
In kotline (since the language is not fundamental), nullable types come to the rescue with the fight against NPE. Each class generates two types, for example for the Person class it would be Person and Person?. Method signatures can explicitly specify which types are valid. If Person?, then the compiler will force you to handle the null case. Also, you will not be able to return null from the method if you declared the Person type as a result. The program just won't compile. All to ensure that null does not come from unexpected places, is processed and does not drop the program.

D
doublench21, 2019-11-08
@doublench21

The concept of optionals is not new and simple as a bath leaf. It's just an enum:
(You can see the full implementation here )

enum Optional<Wrapped>: ExpressibleByNilLiteral {
  // The compiler has special knowledge of Optional<Wrapped>, including the fact
  // that it is an `enum` with cases named `none` and `some`.
  /// The absence of a value.
  ///
  /// In code, the absence of a value is typically written using the `nil`
  /// literal rather than the explicit `.none` enumeration case.
  case none

  /// The presence of a value, stored as `Wrapped`.
  case some(Wrapped)

  /// Creates an instance that stores the given value.
  @_transparent
  public init(_ some: Wrapped) { self = .some(some) }

 //...

BUT people by nature don't like complexity, even if the idea itself is good enough. Nobody wants to write Optional<MyClass>.some(myObj)the accompanying stuff every time... This is where the Swift
language comes on the scene , where the concept of Optionals is taken to the absolute and supported at the compiler level. But what does it give? There are a lot of conveniences: no need to write a complete type, we added the corresponding literals ("!", "?", "nil") and, in general, work with enumeration ( ) is done in the form of a regular standard type, Alya some. ------------------------------------ Why Optional is needed and why over null is not allowed... ?enum OptionalInt
You can't because, by its very nature, null points to a pointer that doesn't currently point anywhere. Optional, on the other hand, allows you to extend this concept not only to pointers (that is, to reference types), but also to the most common types (value types).

B
briahas, 2019-11-08
@briahas

You can't pour borscht into the word "plate" can you? You need an object - a plate.
It turns out that there is an Optional type in the brain that combines a word (which is essentially non-material = null) and a real object / type ... With the compiler somewhere + - everything is the same.
(Slightly frivolous explanation, but I think it will lead to the right thoughts)

M
mayton2019, 2019-11-09
@mayton2019

Unlike SQL, Lisp and other technologies where null/nil has semantic semantics and allows you to perform operations in Java, any attempt to apply any method to null throws an immediate NPE. This means that the programmer FORGOT to initialize the object. This is a gross error and the saddest thing is that it is not checked by the compiler. The use of Optional in streams is necessary to protect the application of map/filter from sudden NPE.
The example that the author gave at the beginning of the topic is simply unsuccessful. It doesn't reveal the benefits of Optional. See the article on Baeldung's website. She is more visual.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question