Comparing Optionals and Null in Swift, Scala, Ceylon and Kotlin

Today it's clear that representing optional values with Null was not the best idea. Several modern languages model this problem with explicit nullable types or Option Monad (after the Haskell Maybe Monad). As Option in Scala has influenced my programming style heavily over the last years, I wanted to compare how other languages deal with this. I did not include Groovy although it was one of the first (the first?) JVM language to safely dereference null values because I currently have no interest in Groovy.

The languages I compare in code fragements are Scala, Kotlin, Ceylon and Swift.

Set value (languages may infer type, added type for clarity)

Accessing values

Forcing to get a value

Else values for empty/Null


Alternative chaining

Interesting in Kotlin

Interesting in Swift

Interesting in Scala, see For

Some thoughts

To me it looks like the combination of special syntax (Type?, !. and ?.) together with a Optional type in Swift looks clearer than Scala code for some cases but is more powerful and has clearer types than modeling optional in Kotlin/Ceylon (e.g. usage of flatMap chaining, flatten, Applicatives etc.). Interesting to see !! in Kotlin visually signaling that this is a dangerous operation. Ceylon else looks really nice for alternative chains, Kotlin return for the alternative case looks nice for method guards.

If you have feedbacks about things I've got wrong or forgot reply to @codemonkeyism or start a Hackernews thread.