Options in scala and java are something that I am struggling to understand and work with. I understand its there in order to eliminate 'null' handling hell. Frankly, I think its introducing another kind of hell!
The way I deal with nulls in java is to do something like:
String test = null;
if(test==null) // do something
else // do something else
This sort of decision is what I am seeking to do when I switch to Options.
But there is no method in the Option class in both scala and java to say, if null do something, else do something else.
There is a way to default the value in case of subject being null, such as
//in scala
test.getOrElse("defaulted")
I was wondering why there cant be methods such as the implicit class I have written to 'pimp up' a Scala option
object Definitions{
implicit class OptionExtensions[$Data](option: Option[$Data]){
def perform (found: ($Data)=>Any, notFound: ()=>Any): Any={
option match{
case Some(data)=> found(data)
case None=> notFound()
}
}
}
}
Please ignore the badly named method. But with this now written, I could supposedly use an option like this:
import Definitions._
val test : Option[String] = None
var builder =new StringBuilder
test.perform(builder ++= _, ()=>addError("not found"))
//or
println(test.perform(_.reverse, ()=>{"something else"}))
def addError(error:String)={
println(error)
}
Instead I am forced to write match and case for handling anything to do with Options. I must be doing something wrong. Most likely, my understanding of how to use Options is flawed. The above way of handling is not in the Option class by default because of a reason. Now what could that reason be?
Anyas the type for your methods (or method parameters) brings you to a real hell (you lose all the power the type system offers you). That said, the most idiomatic way to use anOptioninstance is to treat it as a collection or monad and usemap,flatMap,filter, orforeach.foldto do this:test.fold(addError("not found"))(builder ++= _)