Option!T

Meta via Digitalmars-d digitalmars-d at puremagic.com
Tue Jul 1 22:39:50 PDT 2014


On Wednesday, 2 July 2014 at 04:26:50 UTC, Wanderer wrote:
> Uhm, I'm sorry, but I don't see any difference between two 
> approaches - null-not null vs. one value/no value.
>
> In both cases, there is a possibility of a situation when the 
> value that "should be there", is not there. It can be either 
> because it's not available yet, or because programmer made a 
> mistake in the code. But in either case, when you try to use 
> the value that's "not there" without cheking first, you get a 
> runtime error.
>
> Correct me if I'm wrong, but "Option" being suggested here, is 
> just a nullable reference in disguise.

You're exactly right. Where nullable is most useful is with types 
that don't have null values. Ints, floats, chars, etc. Then in 
some hypothetical function IndexOf, instead of returning -1 or 
int.max or throwing an exception or whatever else we can think 
up, we simply return a Nullable!int to specify that the index of 
a particular item may exist or not, depending on if that item is 
in the array.

Nullable!int IndexOf(int[] arr, int val)
{
     foreach (int i, n; arr)
     {
         if (n == val)
         {
             return Nullable!int(i);
         }
     }

     return Nullable!int();
}

This pattern is very prevalent in functional languages, even when 
returning objects from functions, because many functional 
languages do not have nullable objects. Therefore, the concept of 
"null" is encoded in the type system as some kind of Option type.


More information about the Digitalmars-d mailing list