Either[String,Unit] - is it idiomatic ? Is there a more idiomatic type for this?

819 views Asked by At

What to return on success in add ?

Currently I return Unit, is there a more idiomatic way ?

I mean, the Either[String, Unit] does not feel right, because Right is meant to return a value, since it has a type parameter.

The method can fail or complete with success, however when it completes with success then there is nothing to return, so I just return Right(). I wonder what is the idiomatic way to describe such situation?

What would be a good type to represent this situation ?

import scala.collection.immutable.HashMap 
import scala.concurrent.ExecutionContext

object UUID{   
     def apply():UUID= UUID(java.util.UUID.randomUUID().toString) 
} 

case class UUID(id:String) case class Ref[T](c:Class[T], id:UUID) {
     override def equals(that:Any)=id.equals(that)   
     override def hashCode()=id.hashCode() 
} 

case class RefVal[T](r:Ref[T],v:T)

package container {

  import scala.concurrent.Future

  trait MapContainer[T] {
    var map: HashMap[Ref[T], RefVal[T]] = HashMap[Ref[T], RefVal[T]]();

    private[container] def add(rv: RefVal[T]): Future[Either[String, Unit]] = Future
    {
      if (!map.contains(rv.r)) {
        map = map updated(rv.r, rv)
        Right()
      } else Left("add, class already exists with this uuid :" + rv.r.c)
    }

    private[container] def notExposed=println("cannot run this from outside package 'model'")

    def delete(r:Ref[T]) : Future[Either[String,Unit]]=  Future  {
      if (map.contains(r))
      {
        map = map - r
        Right()
      }
      else Left(r+"element not found")

    }
...
}
1

There are 1 answers

4
C4stor On BEST ANSWER

I think a more idiomatic way would be :

  • Create a custom exception class for your exception case (arguable)
  • Return an Either[Throwable, Map] in the add method, returning the modified map on the right side

Btw, you can use codereview.stackexchange for, well, code review needs :)

Edit : as @massg pointed, at this point, Try[Map] has exactly the semantic of Either[Throwable, Map], and is indeed more weel suited