Saturday, July 5, 2008

Option class for better null

Now that I've been using Scala for a while, I'm starting to learn a few niceties that Scala provides. One of these is the Option class.

The Option class is designed to replace/remove null pointer exceptions. So... first of we'll show you how it works. To create an option variable, you declare it as "Option[T]" where T is the type you'd like to get out.


class MyClass {
var possiblyEmptyString : Option[String] = None;
}


In the above example, I'm creating a class with a "possibly empty string". I'm assigning it a value of "None". Think of None as a version of null, but nicer.

When you're ready to assign a value to an "Option" you do so like this:

def assign = {
possiblyEmptyString = Some("String");
}


How do we make use of an "Option"? One of the following ways:

def doStuff = {
// 1) Check to see if it's defined
if(possiblyEmptyString.isDefined) {
doStuffWith(possiblyEmptyString.get))
}

// 2) Use a default
doStuffWith(possiblyEmptyString.getOrElse("MyDefault"))

// 3) Patern matching
possiblyEmptyString match {
case Some(string) => doStuffWith(string);
case None => logError("STRING UNDEFINED!");
}
// 3) Foreach
possiblyEmptyString foreach { string => doStuffWith(string) }
}



So.. first of, you can check an option to see if it's "empty" (None) or "defined" (Some). I'm also using the "get" method here. Get will return the value of the option, or do something crazy if the option isn't defined. (Not sure what as I haven't done that yet).

Next up is the getOrElse. getOrElse will return the value in the option (if not None), or return the value (or return value of the closure) passed in as an argument. This is my favorite to use for connections. I have some connections that will set themselves to None on errors. Everytime I do something with the connection I call getOrElse(reconnect). Reconnect will reconnect to the socket/database/etc. AND reset the Option[Socket/Connection/etc] to point to the new connection AND return the new connection. This means that if the option is None, i will automatically reconnect, but if the connection is ok, we return it. This allows the code to go along blissfully unaware of connection issues.

The next option is my favorite for using an Option value. You do pattern matching on the value and extract it correctly (or None). I think I may cover pattern matching in more detail in my next post, as I'm running out of time here.

Lastly is the foreach loop. It's guaranteed to only return the value in a Some object, so the closure won't get called for a None object. I'm not quite a big fan of the syntax, but it works.

0 comments: