Blankman
Blankman

Reputation: 267010

Calling andthen on 2 functions don't require them to have the same return value?

I am trying to understand how the below code works. How is it that the f1 function can chain the calls using andThen when the return types don't align exactly?

It seems the Future[Int] value of inner2 is lost when I call it last in the function f1.

So from what I understand the flow works like this:

  1. f1 is called passing user as an argument.
  2. inner1 is called, passing user and it returns the Future of either boolean or user.
  3. the andThen is called, passing user as an argument, but somehow also passing the return value of the call to inner1? Is this curried??
  4. Doesn't inner2 respond with a different return type, how is the Future[Int] just lost?

The code:

def f1(user: User): Future[Either[Boolean, User]] = 
  inner1(user) andThen inner2(user)
    
def inner1(user: User): Future[Either[Boolean, User]] = ???
def inner2(user: User): PartialFunction[Try[Either[Boolean, User]], Future[Int]] = ???

Upvotes: 1

Views: 136

Answers (1)

jwvh
jwvh

Reputation: 51271

inner1() returns a Future.

As @LuisMiguel has pointed out, you're calling andThen() on that Future

andThen(), on a Future, takes a PartialFunction[Try[T],U] where T is the Future's return type, in this case Either[Boolean,User].

The PartialFunction, i.e. inner2(), is applied as a side-effecting callback on the Future, so its return value, the Future[Int] in this case, is discarded.

Upvotes: 2

Related Questions