Search code examples
scalaoption-typenullablescala-option

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


I need to return values, and when someone asks for a value, tell them one of three things:

  1. Here is the value
  2. There is no value
  3. We have no information on this value (unknown)

case 2 is subtly different than case 3. Example:

val radio = car.radioType
  1. we know the value: return the radio type, say "pioneer"
  2. b. there is no value: return None
  3. 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) => 
}

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]