Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using Try[Unit] the proper way?

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?

like image 256
Karda Avatar asked May 27 '14 20:05

Karda


People also ask

Why use Try in Scala?

Try was introduced in Scala 2.10 and behaves as a mappable Either without having to select right or left. You can see how, instead of using explicit try and catch to treat exceptions, Try is used to encapsulate the operation which is always an instance of either Success or Failure.

What is try in Scala?

The Try type represents a computation that may either result in an exception, or return a successfully computed value. It's similar to, but semantically different from the scala. util. Either type. Instances of Try[T] , are either an instance of scala.


1 Answers

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)
}
like image 167
Andrzej Jozwik Avatar answered Sep 27 '22 18:09

Andrzej Jozwik