Is there a way to transform a Tuple of Resources into a Resource of Tuple?

63 Views Asked by At

I'm trying to port Scala2 / shapeless code to Scala3, and one thing I miss is a way to convert a HList of Resource to a single, type-safe Resource.

In Scala2, I am able to use cats.sequence.Traverser's traverse

type T = A :: B :: HNil

val resourceH: Resource[F, T] = (resourceA :: resourceB :: HNil).traverse(...)

However, cats remove the Traverser, Shapeless-3 removed HList, and mentions that the official replacement is simply using Tuple. Is there a way to do the above using plain, arbitrary arity Tuple instead of HList ?

What I've tried so far is

  • (type unsafe) iteration over the Resource tuple's product. Not only I am betraying the compiler, it will fail at runtime to cast back into the right tuple type
  • trying to build a Resource of Tuple by recursion. I just can't seem to get the syntax right though
1

There are 1 best solutions below

0
Daenyth On

A tuple of Resource can be composed applicatively, either serially or in parallel

import cats.syntax._
(rA, rB).tupled    // Resource[F, (A, B)], serial acquire
(rA, rB).parTupled // Resource[F, (A, B)], parallel acquire

And similarly with mapN or parMapN to directly apply a function instead of just having a tuple value from the resource