Spreadsheet for differences between let, with, run, apply and also


But Optional is not a super type of Iterable or Collection. The let method is on every object. So the fact that map already exists on Optional is also an argument against using map as name for let.


  • collection/iterable-like types have a map method to map their content (each item one by one)
  • Optional has a map method also to map its content (a single item)

They also both have the global let method, like any other object, to map themselves, not their content. So I don’t believe the langage designers could have named this method map, because Optional and collections would have had 2 overloads of it: one that takes the item type as input, and one that take the collection itself (or the Optional) as input.


Actually from a functional point of view both Optional and Collection are Monads, which is why they both have a map method. Since nullables in Kotlin are kind of a “primitive” type they dont have that.
For me a clear indication that KIotlin is not a functional language, but a OOP language with functional elements.


I’m not a Kotlin expert yet, I’m barely scratching the surface of the language, but I believe extension functions could be defined on Any?, so that we have map and flatMap on nullable types, instead of requiring the use of Optional.


You could define map and flatMap for Any? using extension methods, but what would you gain. Kotlin has uses the ? to interface with nullables. Implementing Optionals function on Any? would just lead to more verbose code.


Why more verbose? We could argue that using map on a nullable would be more natural and less verbose than using ?.let.
In fact, in order to have the convenient functional-like methods of Optional, the developers are forced to actually use that Optional wrapper class instead of the handy built-in nullable types, and I believe that makes things more verbose.

However, I have to admit that most of the time, using the ?. operator for any method call or property access is sufficient, and we don’t actually need a map() call, but @svd made me think about it from a functional programming’s perspective.


Ok maybe more verbose is not the problem. That still does not remove some of the other problems.
The first is that it adds a second way to do the exact same thing. People who know optionals will use map which will confuse people not familiar with the topic. Also you drop the ? which means you are no longer able to see at first glance whether you deal with a nullable value or not. Yes there are a few other functions defined on nullable types but they all make it clear that the value might be null as most of them are extended null checks (String?.isNullOrEmpty()).

Also if we want to continue this discussion I suggest we move it to new topic.