简体   繁体   中英

Making code more scala idiomatic

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 eg 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 eg 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?

有一种想法可能会使processDefinition.getDiagramResourceName()返回一个Option ,因此您可以检查结果是Some(x)还是None

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) .

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM