I would like to know if it is possible to create some kind of "chain of method calls", while all methods return the same way. [Error, Result].
What I would like to do is: call all methods sequentially, and when the method returns Left (Error), then stop the method calls and return the first left ones found in the call chain.
I tried something with a fold, map, projections ... but I am new to Scala and have not found anything elegant solution.
I tried something like this:
def createUserAndMandatoryCategories(user: User) : Either[Error,User] = { User.create(user).right.map { Logger.info("User created") Category.create( Category.buildRootCategory(user) ).right.map { Logger.info("Root category created") Category.create( Category.buildInboxCategory(user) ).right.map { Logger.info("Inbox category created") Category.create( Category.buildPeopleCategory(user) ).right.map { Logger.info("People category created") Category.create( Category.buildTrashCategory(user) ).right.map { Logger.info("Trash category created") Logger.info("All categories successfully created created") Right(user) } } } } } }
But that will not work. And in any case, I really don't like the indentation. Also, I would like to convert Error to a new line describing the problem (I think I should use fold?)
I am looking for something like this:
val result : Either[String,CallResult] = call1.something("error 1 description") .call2.something("error 2 description") .call3.something("error 3 description") .call4.something("error 4 description")
Is it possible to do such a thing with Scala? Perhaps using both options and option?
One limitation will also be that if the first call is not being made, other calls should not be made. I do not want a solution where I call everything and then join eithers.
Thank!
scala functional-programming monads either
Sebastien Lorber Aug 24 '12 at 10:05 2012-08-24 10:05
source share