Java Scala – Alternatives to Null Values and Option-Like Types

conceptsjavanullscala

Related to this question i want to know if there is a concise way to eleminate null values out of code in general or if there is not.

E.g. imagine a class that represents a user with birthday as attribute which can be set but does not have to, which then means it's null. In scala and similar languages one could use the Option type to describe this and i see why this is better then just having a regular null value as one would code it in java.

However i wonder if this is the right concept or if we can do it better in this case and even in general.

I came to the idea that we could replace the users birthday (and other optional or possibly unknown/unset attributes) with a list of possible optional attributes. So we could have like

ourUser.getOptionalAttributes()
// could return a list [Date Birthday, Float Height, Color Eyecolor]
// or just [Color Eyecolor]
// or even an empty list

However using a regular list would mean that we could store multiple birthdays e.g.
So we needed a way to tell the compiler that the list may only contain one Birthday type.

Am i totally on the wrong track here and are option types the (philosophical) correct way to express optional attributes?
Also, are there additional concepts for handling the logic of optional attributes other than nullable types and option-like types?

Best Answer

What is a type?

A type is meta data that can be used, at compile time or run time, to describe the shape of our data.

trait A { val b: X; def c(y: Y): Z}

So we know in our program that when ever we see an a: A, we know that a has the shape of A so we can call a.b safely.

So what shape does null have?

null has no data. null does not have a shape. String s = null is allowed as null has no shape, so it can fit any where. MikeFHay above says that an empty collection can be thought of as a null object. This is wrong, an empty collection has exactly the same shape as any other collection.

If a field can be null, then we can no longer rely on a.b to be safe. The shape of the data in this field is not truly A, only potentially A. The other shape it can be is null. That is the shape of this field is a union of A and null.

Most languages allow unions to be implemented as a tagged union. Scala's Option type is a tagged union of None | Some(a:A). Like wise Ceylon adds a ? postfix for types that say that the type may be null as in String? s = null.