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)

//Scala: Some/None of type Option[String]
var h:Option[String] = "Hello".some

//Kotlin: Value and Null
var h:String? = "Hello"

//Ceylon: Value and Null
String? h = "Hallo"

//Nice: Value or Null
?String h = "Hello"

//Fantom: Value or Null
Str? h := "Hello"

//Swift: Some/None/Nil of type Optional<String>
var h:String? = "Hello"
var h:Optional<String> = Optional("Hello")

Accessing values

//Scala: Some(Value) or None
val l =

//Kotlin: Value or Null
val l = h?.length() 

//Ceylon: Value or Null
Integer l = h?.length

//Nice: Value or Null
let l = (h == null) ? 0 : h.length();

//Swift: Optional(Value) or None/Nil
var l = h?.length()

Forcing to get a value

//Scala: get may throw exception

//Kotlin: may throw NPE

//Swift: ?

Else values for empty/Null


val l = if (h!= null) h.length() else -1
val l = h?.length() ?: -1 

Integer l = h?.length else -1

// Ceylon: Alternative 'else'
String greeting = (h else "Hello") + " there!"


//flatMap or map depends on call1, call2




Alternative chaining

val name = firstName.orElse(lastName).getOrElse("Guest")

// Ceylon: Chain 'else'
String name = firstName else lastName else "Guest"

Interesting in Kotlin

//Operator can return from method
val hello = h ?: return null

Interesting in Swift

//Dereference a value
if let l = h?.length {
  println("Length: \(l)")
} else {
  // was empty

// when getPerson returns Optional
if let person = getPerson { = "Code Monkey"
  person.age = 99

Interesting in Scala, see For

// h and name are Options
// Returns Option[String]
// Returns None if any Option is None
// for is more powerful than this
// as this is a simple example
for ( hello <- h;
      name <- n ) 
yield {
      hello + ", " + name 
// templating did not work in WordPress

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.

Stephan Schmidt Administrator
CTO Coach , svese
Stephan is a CTO coach. He has been a coder since the early 80s, has founded several startups and worked in small and large companies as CTO. After he sold his latest startup he took up CTO coaching. He can be found on LinkedIn or follow him in Twitter.
follow me