0
votes

I came across following java like code in Scala project. how to make it more Scala idiomatic with no side effects (exception handling appropriately) ?

I am thinking to use scalaz disjunction / (I know I can use Scala either too but like right biased more I guess). in a function there are a few such if checks(one above is one example) which throw one or the other type of exceptions. how to make such code more Scala idiomatic?

EDIT: Question is not around how to convert Java null checks into Scala Idiomatic, which I am already doing. for e.g. following

hpi.fold(throw new Exception("Instance not found for id " + processInstanceId)) { h =>
  val pi = new ProcessInstance(taskResponse)

Now return type of the existing function is some value say "ProcessInstance" for e.g. but in my opinion is misleading. caller would never know if this will throw an exception so my question is more around returning Either[Error,Value] from such functions. And if I have a few such exceptions being captured into a single function, how to accumulate them all and reflect into return type?

3

3 Answers

1
votes

One thought might making processDefinition.getDiagramResourceName() return an Option, so you can then check whether the result is Some(x) or None.

1
votes

Using scalaz and being idiomatic this is probably what I would end up with (subject to refactoring):

for {
    pd <- Option(processDefinition.getDiagramResourceName()).\/>("Diagram resource could not be found")
} yield pd

So if you have null you get back Left("Diagram resource could not be found") otherwise you get Right(DiagramResourceName).

0
votes

An approach based in case classes where different subclasses of names, references or labels may be defined,

trait ResourceName
case object MissingName extends ResourceName
case class DiagramResourceName(name: String) extends ResourceName
case class AnotherResourceName(ref: Int) extends ResourceName

processDefinition.getDiagramResourceName() match {
  case DiagramResourceName(name) => println(s"name $name")
  case MissingName               => throw new ActivityException(errorMessage)
}