Convert List to HList List

I want to have a common list of different types, and I want to get objects of a certain type.

I have this structure:

trait Parent
case class A() extends Parent
case class B() extends Parent
case class C() extends Parent

I can define different lists with different sizes:

val list:List[Parent] = A() :: B() :: C() :: C() ::Nil //or any size or ordering

I want to include this at run time in the Hlist from A, B, C, C..toHlist [] I need the types of elements that should be displayed at run time. What would be a shameless way? Is there a way to convert it to tuples?

+4
source share
2 answers

You cannot do this. note that

must be concluded at runtime

is a contradiction. Type inference only works at compile time.

In other words, when you write something like

val list: A :: B :: C :: C :: HNil = ...

list . , . , , toHlistMagical:

val list: List[Parent] = A() :: B() :: C() :: C() :: Nil
val hlist = list.toHlistMagical  // infers to  A :: B :: C :: C :: HNil

:

def getHlist(list: List[Parent]) = list.toHlistMagical

, ? , , , A, B, C, C :

getHlist(C() :: B() :: A() :: A() :: Nil)

Any, list, HList, .

toHlist :

def getHlist(list: List[Parent]) = list.toHlist[A :: B :: C :: C :: HNil]

getHlist Option[A :: B :: C :: C :: HNil], , toHlist list Some, None, .

+3

HList:

def listToHList(x: List[_]): HList = {
  if(x == Nil) HNil
  else x.head :: listToHList(x.tail)
}

:

listToHList(list).asInstanceOf[A :: B :: C :: HNil]

0

All Articles