Scala: Something like Option (Some, None) but with three states: Some, None, Unknown

nullable, option-type, scala, scala-option

Solution

Here's a barebones implementation. You probably want to look at the source for the Option class for some of the bells and whistles:

package example

object App extends Application {
  val x: TriOption[String] = TriUnknown

  x match {
    case TriSome(s) => println("found: " + s)
    case TriNone => println("none")
    case TriUnknown => println("unknown")
  }
}

sealed abstract class TriOption[+A]
final case class TriSome[+A](x: A) extends TriOption[A]
final case object TriNone extends TriOption[Nothing]
final case object TriUnknown extends TriOption[Nothing]

Problem

I need to return values, and when someone asks for a value, tell them one of three things: - Here is the value - There is no value - We have no information on this value (unknown) case 2 is subtly different than case 3. Example: ``` val radio = car.radioType ``` - we know the value: return the radio type, say "pioneer" - b. there is no value: return None - c. we are missing data about this car, we don't know if it has a radio or not I thought I might extend scala's None and create an Unknown, but that doesn't seem possible. suggestions? thanks! Update: Ideally I'd like to be able to write code like this: ``` car.radioType match { case Unknown => case None => case Some(radioType : RadioType) => } ```

Original source