16

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?

jub0bs
  • 60,866
  • 25
  • 183
  • 186
Karda
  • 303
  • 2
  • 8
  • 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? – Dirk May 28 '14 at 09:26
  • 2
    Yes, `Try[Unit]` is perfectly fine. – Alexey Romanov May 28 '14 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]`. – Alexey Romanov May 28 '14 at 11:04

1 Answers1

17

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)
}
jub0bs
  • 60,866
  • 25
  • 183
  • 186
Andrzej Jozwik
  • 14,331
  • 3
  • 59
  • 68