How is the below repository being threaded (passed) into each function call?

77 views Asked by At

I was sure the below underscores are unit meaning function return value is ignored. (The below is taken from book functional and reactive domain modeling). If that's correct then I have a question about the below code:

case class AccountRepository(no: String)


trait AccountService[Account, Amount, Balance] {
  def open(no: String, name: String, openingDate: Option[Date]): AccountRepository => Try[Account]
  def close(no: String, closeDate: Option[Date])AccountRepository => Try[Account]
  def debit(no: String, amount: Amount): AccountRepository => Try[Account]
  def credit(no: String, amount: Amount): AccountRepository => Try[Account]
  def balance(no: String): AccountRepository => Try[Balance]
}


object App extends AccountService {
  def op(no: String) = for {
    _ <- credit(no, BigDecimal(100)) // isn't underscore here mean we neglect the return value as its in most cases unit? this mixes me up.  How do we refer again to the return value if it goes into the underscore which is normally used for unit response.
    _ <- credit(no, BigDecimal(300))
    _ <- debit(no, BigDecimal(160))
    b <- balance(no)
  } yield b
}

scala> op("a-123")
res0: AccountRepository => scala.util.Try[Balance] = <function1>

Will this code work correctly? It will, provided we give some additional power to Function1, which is the type that gets threaded through the comprehension.

So I should be passing to res0 the repository - I don't get how is the repository being throttled to each credit/debit method above? I understand the op returns a function from repository to account however what mixes me up are all these underscores - doesn't underscore means in for comprehension we get rid of the function return value? and if we ignore the returned value then how can we pass those functions the repository?

1

There are 1 answers

0
Jas On

_ does not imply the return value is neglected only that we don't refer to it in code.