简体   繁体   中英

Scala Either with Unit

I am curious about the proper way of doing this. Suppose I want to signal success or failure from a method. Is this acceptable, if there is nothing I want to say in case of success, other than it succeeded?

def fn(): Either[Throwable, Unit]

And what is the proper way to return a Right() from this method, as a success? Apparently just returning Right() gives a deprecation warning (Adaptation of argument list by inserting () has been deprecated).

I can also probably do Option[Throwable], but that doesn't keep with the spirit of how I read Option. Or maybe return the result of scala.util.Try and evaluate Success/Failure?

-- On the deprecation warning, just FYI.

Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_101).
Type in expressions for evaluation. Or try :help.

scala> def fn:Either[Throwable, Unit] = { Right() }
<console>:11: warning: Adaptation of argument list by inserting () has been deprecated: this is unlikely to be what you want.
        signature: Right.apply[A, B](b: B): scala.util.Right[A,B]
  given arguments: <none>
 after adaptation: Right((): Unit)
       def fn:Either[Throwable, Unit] = { Right() }
                                               ^
fn: Either[Throwable,Unit]

您可以使用Unit作为类型并返回()

def fn(): Either[Throwable, Unit] = Right(())

I would say that it depends on the kind of API that you are looking for.

def fn(): Either[Throwable, Unit] sounds pretty non-idiomatic to me. If the main result you expect of the function is a side effect, then there doesn't seem to be a use in using an Either . Did this come up because it's the terminal operation of a monadic operation chain?

It's become less popular and less idiomatic these days, but I would probably go with a Try[A] and handle the cases there. The other idiomatic choice would be to, rather than shuffle exceptions in your Either , to create a sealed trait hierarchy of all your error kinds and return those from your effectful function rather than raw Throwable instances.

I'm not seeing the error you note when calling Right() or Right( () ) at the REPL, what version of scalac are you using?

You should return Option[T] . Either[T, Unit] doesn't contain any more data than Option[T] and if T is some error type in your domain then it's also pretty readable and easy to understand ( Throwable is a bit suspicious to me but that is a discussion of its own)

def fn(): Option[Throwable] = ???

Reading the above type as: Some(e) means there is an error, None means there was no error.

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