• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Optional & Stream.empty().min()

 
Ranch Hand
Posts: 127
5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

I would like to know what is the Optional type is returned from the Stream.empty().min().

Does it always returned Optional <Object> when the stream is empty?




Thanks!
 
Marshal
Posts: 79177
377
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
So what type will a non‑existent object have? Isn't that a self‑contradictory question? You can't even get null, which hasn't got a type anyway, from Optional.empty. You could only get a null if you use the nullable method.
The expression evaluates to whatever you have declared it as. If you declare it as Optional<XYZ>, then you have to write Stream.<XYZ>empty(). and the compiler will see the Stream as a Stream<XYZ>, but not the runtime. Remember that the generic type is erased at runtime and the runtime type of the variable you declared and the Stream are Optional and Stream full stop.

Moved discussion to our Streams forum.
 
henry leu
Ranch Hand
Posts: 127
5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I see.

Stream.empty().min( (a, b) -> 6) is equivalent to Stream.<Object>empty().min( (a, b) -> 6).
And therefore Stream.<Object>empty().min( (a, b) -> 6) can be assigned to Optional<?> or Optional<Object>.

And if I explicitly say Stream.<Stream>empty().min( (a, b) -> 6), then I must assigned it to Optional<String> or Optional<?>.

 
Campbell Ritchie
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

henry leu wrote:. . . if I explicitly say Stream.<Stream> . . .

You mean Stream.<String> I hope.
Yes. The Stream doesn't have an identifiable type at runtime; at compile time the resultant Optional<T> can be assigned to Optional<?> or Optional<String>. But not Optional<Object>. That would represent a covariant type, and as you know, generic types count as invariant.
reply
    Bookmark Topic Watch Topic
  • New Topic