Search code examples
scalashapelesshlist

Can I use shapeless to return the same arity of HList as passed HList?


Here is an example. I'm trying to wrap some external api that accepts and returns the same arity of List:

def externApi(args: List[Int]): List[String] = args.map(_.toString)

I thought this was a good excuse to learn shapeless as it seems like something that HList would be able to do.

def foo(args: HList): HList = ???

How can I encode in type that passed HList and returned HList are of the same arity?


Solution

  • To expand on @stew's comment, you can use Sized to enforce an equal arity between the lists.

    import shapeless._
    import syntax.sized._
    
    def externApi[N <: Nat](args: Sized[List[Int], N]): Sized[List[String], N] =
        args.map(_.toString)
    

    Usage:

    scala> externApi(Sized[List](1, 2, 3, 4))
    res0: shapeless.Sized[List[String],shapeless.nat._4] = List(1, 2, 3, 4)
    
    scala> res0 foreach println
    1
    2
    3
    4
    

    I'm far from a shapeless expert, so I don't know if there is a way to do this with an HList, but it seems like your collections are homogeneous anyway.