by jolmg · 7y ago · 0 comments
In Haskell, it's pretty much impossible to have unexpected nulls because the ability to return nulls is something that is expressed in the type and needs to be handled before working with the possible type to be able to pass the type-check of the compiler.
For example, if I had a function:
findFistOdd :: [Int] -> Maybe Int
That returned the first odd number in a list of numbers, the Maybe wraps the return value so the result is either `Nothing` or `Just someNumber`. I can't work with the result directly like 1 + findFirstOdd [2,3]
It would fail the type check, because I need to tell the compiler what the program should do if findFirstOdd couldn't find an odd number. (1 +) is certainly not expecting a NULL as its argument type is Int. I can tell it, "Just die if that happens": 1 + (fromMaybe (error "couln't find odd number") $ findFirstOdd [2,3])
or I can tell it to work on the inside value if it's there, returning Just (1 + someOddNumber) if it's there or Nothing if it's not: (1 +) <$> findFirstOdd [2,3]
Conversely, if a function says it returns an Int: addOne :: Int -> Int
That means it returns an Int, guaranteed. That's never going to be some null value. It's not something you'd ever have to consider.Kind of wish all languages were like this. Nulls are probably the cause of most unexpected exceptions and it could be something that could always be caught without even running the program.
https://docs.oracle.com/en/java/javase/12/docs/api/java.base...
Of course, an Optional reference can still be null because it's still Java. There are also other implementations of Maybe-like types, and implementations of Either-like types, etc in the Java ecosystem.
a) Interop with Java APIs (Kotlin doesn't force you to check every return type from a non-Kotlin call)
b) If you use !! to cast away nullness. Good Kotlin style can almost always avoid such cases.