How to convert a common HList to a list

I have:

trait A[T] class X class Y object B { def method[H :< HList](h: H) = h.toList[A[_]] } 

The parameter h of method will always be the HList of A [T], like the new A [X] :: new A [Y] :: HNil.

I would like to convert the HList to the list [A [_]].

How can I get this with generic code because the HList object does not have a toList () method?

+6
source share
1 answer

A compiler error should inform you of the desire for an implicit value of type shapeless.ops.hlist.ToList[H, A[_]] . You can provide one of them by adding an implicit argument list to your method signature:

 object B { def method[H <: HList](h: H)(implicit ev: ToList[H, A[_]]) = h.toList[A[_]] } 

Now you can write the following:

 val someAs = new A[Int] {} :: new A[String] {} :: HNil 

And then:

 scala> B.method(someAs) res0: List[A[_]] = List( $anon$1@5dd508ef , $anon$2@4d3db309 ) 

Almost every HList operation will require this kind of implicit evidence.

+8
source

Source: https://habr.com/ru/post/974096/


All Articles