Either[String,Unit] - 是惯用的吗?有没有更惯用的类型?

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

return 在 add 中成功要做什么?

目前我returnUnit,有没有更地道的方法?

我的意思是,Either[String, Unit] 感觉不对,因为 Right 意味着 return 一个值,因为它有一个类型参数。

该方法可以失败或成功完成,但是当它成功完成时,就没有什么可以 return,所以我只是 return Right()。我想知道描述这种情况的惯用方式是什么?

用什么类型来表示这种情况比较好?

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

    }
...
}

我认为更惯用的方式是:

  • 为您的异常情况创建自定义异常class(有争议)
  • Returnadd方法中的一个Either[Throwable, Map],右侧返回修改后的map

顺便说一句,您可以使用 codereview.stackexchange 来满足代码审查需要:)

编辑:正如@massg 指出的,在这一点上,Try[Map] 具有 Either[Throwable, Map] 的语义,确实更适合