I don't mind the idea of Open/Maybe type, although I think it is already availabe in Kotlin because of the nullable types already making it clear what is optional or not. But, I would never like to see this forced to be used from things like myMap.get("key") since you then have to always dereference. Extensions can have myMap.getOptional("key") but let's not break the closeness to the Java built-in collection classes.
I find that there are patterns I use now that make me not even think about Optional very often. For example:
myMap.ifContains(“key”) { value -> … do something … }
myMap.ifNotContains(“key”) { … do something else … }
and variations that deal with what present means (null, empty string, empty string once trimmed).
These extensions make my code clearer what I intend anyway than guessing from the if statements (does each if statement really need null check, trim().isNotEmpty()?). You can also extend to create patterns like:
val myMap = mapOf(“one” to 1, “two” to 2)
myMap.ifContains(“one”) { value ->
println(value)
} otherwise {
println(“not found”)
}
Or maybe that is backwards for reading and we are extending the wrong thing. String could be extended to get the words in the right order (for English sentences):
“one”.isPresentIn(myMap) { value ->
println(value)
} otherwise {
println(“not found”)
}
Outside of this use case, I also have patterns like “add a default, but let me know you used the default” where I have data classes like:
data class PropertyValue(val value: String, val wasDefaulted: Boolean)
And then my property class would have a few varations of getting properties:
props.getValue(“forProperty”) -> String
props.getValueElse(“forProperty”) { … generate default … } -> String
props.getValueElse(“forProperty”, “literalDefault”) -> String
props.getValueDefaulted(“forProperty”) { … generate default … } -> PropertyValue
props.getValueDefaulted(“forProperty”, “literalDefault”) -> PropertyValue
No optional needed, and it is clearer for this case than a generic Optional would be. And I can avoid the new return class if it doesn’t make sense at the call site (sometimes I don’t care if it was defaulted, other times I need to know).
More ways to skin the cat…