|
I think there's some misunderstanding about what goes on with an Option<T> type in the compiler. In a sane implementation of Option<T>, there's no space premium for using it over T. The compiler compiles Some<T> to a pointer to T, and it compiles None to null. Swift, Rust, and Haskell all do this; I don't know Scala that well, but I'd imagine it would too unless there's some edge case in Scala<->Java interop. Kotlin's nullable types and Option are exactly the same thing, except with some implicit conversions and smart casts available (marked by the IDE). Using Kotlin & Rust syntax, I make the following mental equivalencies: T? <==> Option<T>
maybeNull!! <==> maybeNull.unwrap()
maybeNull ?: default <==> maybeNull.unwrap_or(default)
maybeNull == null <==> maybeNull.isNone()
maybeNull != null <==> maybeNull.isSome()
maybeNull?.method() <==> maybeNull.map(|v| v.method())
maybeNull?.method() ?: default <==> maybeNull.map_or(|v| v.method(), default)
The comparison is even more apparent if you're used to Swift, which has a separate Optional type but the same syntactic sugar as Kotlin for manipulating it.The two ways that Kotlin nullable types differ from Options in other languages is that you have smart casts (if the compiler can prove that the value is never null, you can use it as a normal variable without explicitly unwrapping), and you have automatic coercions from platform types. Also, I almost never use null in idiomatic Kotlin programming. |
This is wrong for Scala, and I think it's wrong for the other cases.
> Kotlin's nullable types and Option are exactly the same thing
Except that it doesn't nest properly. Which means it's not compositional: if you write code that works with T?, it will have surprising behaviour if someone ever passes a nullable type for T. And you can't abstract over it, though that's a more general problem of Kotlin not having HKT.
> Also, I almost never use null in idiomatic Kotlin programming.
How do you represent optionality then? I use Option and None pretty often in idiomatic Scala programming (and when I don't it's usually because I'm using a richer variant on the same thing e.g. Either or a custom sum type appropriate to the business requirements) - there's a reason it's such a common example, it comes up in realistic problems all the time.