vendredi 22 avril 2016

How to change method return types in order to manage errors and exeptions

The following code is in a library (I can't edit it).

trait ATraitInALibraryICantEdit[T] {
  def save(data: T): Future[T]
  // ....
}

Then, in my code, I have :

class MyClass[T] extends ATraitInALibraryICantEdit[T] {
  override def save(data: T): Future[T] = {
    // ...
  }
}

This is simple inheritance. But, in my case, I would like to change the signature of the method to something like (to manage exceptions) :

// Type change : Future[T] --> Future[Either[String, T]]
override def save(data: T): Future[Either[String, T]] = {
  // ...
}

To sum up, my problem is how to change return type of a method in order to adapt it to my way of managing errors.

I guess, I should use a pattern (and not direct inheritance), but I don't know witch one. I don't even kwnow if it's possible without updating the library.

A solution is to use exceptions, I would rather prefer to use monads instead.

Any suggestion ?

Aucun commentaire:

Enregistrer un commentaire