Search code examples
scalafunctional-programmingfor-comprehensiondoobie

List to multiple anonymous/underscore parameters in for-comprehension


I'm kind of new to Scala/functional so I'm not yet able to use technical language.

I'm experiencing problems with a for-comprehension

 val queries =
for {
  _ <- createBanco
  _ <- createBancoMedio
  bankInsertions  <- Update[Banco](insertStr).updateMany(NonEmptyList.fromList(createBankList(1, maxBanks)).get)
  mediumInsertions  <- Update[BancoMedio](mediumInsert).updateMany(NonEmptyList.fromList(mediumList).get)
  bankCount <- BancoStatements.getCount().unique
  bankGetIds <- BancoStatements.getIds(0, maxBanks).to[List]
  bankSome <- BancoStatements.getSome(halfBanks).to[List]
} yield (bankCount, bankGetIds, bankSome)

//Execute database queries, saves them on tuple
val transactionResults : (Int, List[String], List[Banco]) = 
queries.transact(h2Transactor).unsafeRunSync()

I'm trying to refactor the _ <- createBanco & _ <- createBancoMedio, which are both a ConnectionIO[Int] object.

Id like to convert those to a single List(createBanco, createBancoMedio) and then execute transact.

However, i'd be altering the return type of the for-comprehension by doing that. I'd like to know if there is any way on doing that without affecting the for output value

Basically, treat the list as if I was writing multiple anonymous parameters manually.


Solution

  • You can use .sequence to turn a List[G[A]] into a G[List[A]] if G has an Applicative instance, which ConnectionIO does:

    val queries =
    for {
      _ <- List(createBanco, createBancoMedio).sequence
      ...