java.util.Optional support in the standard library
ilya-g opened this issue · 4 comments
This issue is for discussion of the proposal to introduce convenience extensions for java.util.Optional
type in the standard library.
I never defined three distinct methods for unwrapping, in my experience Optional<T>.orNull()
is enough.
For completeness, we propose including the following alternatives to Optional's factory methods
I propose to reconsider this section, should we provide a dedicated constructor for this type, only for completeness?
A standard optionalOf
method can create confusion with other types of Optional
s, like Guava's provided one.
Kotlin does not provide a streamOf
, completableFutureOf
or a publisherOf
.
What should be the type of optionalOf(3)
, OptionalInt
or Optional<Int>
?
I think that Optional.of*
is enough, using Java syntax with Java classes is not so strange for me, factory methods can be shifted in future advancements if required.
I propose to reconsider this section
@fvasco please mind the note in the beginning of that section: it's excluded from the proposal.
While the goal of such addition as stated in the KEEP would be to help with Java interop, I'm afraid providing this many helpers may encourage the use of Optional
within Kotlin code - where nullable types are more idiomatic and benefit from nice and concise operators (and declarations).
Like @fvasco, I believe Kotlin only really needs .orNull()
. This function is useful because the vast majority of interop with Java's Optional
would be to convert Optional
return values of Java functions into nullable Kotlin types, which simply transforms the Java signature into what you would have had from the Kotlin equivalent. Considerations of getOrElse
etc. shouldn't really apply because in Kotlin, you would have received a nullable value in the first place, so after .orNull()
conversion one can just write idiomatic Kotlin code.
Optional
arguments in Java methods are quite rare in comparison to optional return values (there are arguments for avoiding such practice), so I see little benefit in providing factory methods for those, especially since there are existing static factory methods on Optional
that do the job quite OK. IMO this part is the one that would encourage the most to create more Optional
values in Kotlin, which I believe would be a step backwards. (EDIT: this has been excluded from the proposal as of now)
Also, Optional
s are not supposed to represent collections, so the proposed conversion methods (toSet
, toList
, asSequence
) seem semantically debatable. If we consider that we unwrap optionals from Java methods into nullable values, this is the end of the interaction with the Java API surface. We can then use nullable values as if they were returned by Kotlin methods - using other helpers such as listOfNotNull
etc.