I need to return values, and when someone asks for a value, tell them one of three things:
case 2 is subtly different than case 3. Example:
val radio = car.radioType
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) =>
}
An Option[T] can be either Some[T] or None object, which represents a missing value. For instance, the get method of Scala's Map produces Some(value) if a value corresponding to a given key has been found, or None if the given key is not defined in the Map.
The Option in Scala is referred to a carrier of single or no element for a stated type. When a method returns a value which can even be null then Option is utilized i.e, the method defined returns an instance of an Option, in place of returning a single object or a null.
We can test whether an Option is Some or None using these following methods: isDefined – true if the object is Some. nonEmpty – true if the object is Some. isEmpty – true if the object is None.
In Scala, using null to represent nullable or missing values is an anti-pattern: use the type Option instead. The type Option ensures that you deal with both the presence and the absence of an element. Thanks to the Option type, you can make your system safer by avoiding nasty NullPointerException s at runtime.
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]
Don't tell anyone I suggested this, but you could always use null for Unknown rather than writing a new class.
car.radioType match {
case null =>
case None =>
case Some(radioType : RadioType) =>
}
You can grab some stuff from Lift: the Box. It has three states, Full, Failure and Empty. Also, Empty and Failure both inherit from EmptyBox.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With