18

I recently came across the concept of Try/Success/Failure, and I am wondering how to use it for a method that has the return type Unit. Is using Try[Unit] the correct way? Maybe I am too influenced from my Java background, but is it a good idea to force the caller to deal with the problem?

3
  • If the method has no meaningful return type (except for possibly generating a failure), why not Option[MyException] with None being the default case, and Some(exception) being the result in case of errors? Commented May 28, 2014 at 9:26
  • 2
    Yes, Try[Unit] is perfectly fine. Commented May 28, 2014 at 11:01
  • 2
    @Dirk Because you should avoid special cases. If you have one method returning Try[String] and another method taking String and returning Option[Exception], they are harder to use together than if the second method returns Try[Unit]. Commented May 28, 2014 at 11:04

1 Answer 1

19

Try[Unit] is normal. For example, if you persist the entity, you can use:

try { em.persist(entity) } catch{ case ex:PersistenceException => handle(ex) } 

or just

Try(em.persist(entity)) match { case Success(_) => case Failure(ex) => handle(ex) } 
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, I did not know I can also use a catch at this point. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.