Who can explain the meaning of this scala code

I have been reading this code for a long time. I typed it in REPL and it works too.

but I don’t know what is going on here. Why and how does it work?

import shapeless._ case class Size[L <: HList](get : Int) object Size { implicit val hnilSize = Size[HNil](0) implicit def hconsSize[H, T <: HList](implicit tailSize: Size[T]) = Size[H :: T](1 + tailSize.get) def apply[L <: HList](l : L)(implicit size: Size[L]) : Int = size.get } Size(1 :: "Foo" :: true :: HNil) 

Can someone explain this step by step and help me understand what is happening here.

+6
source share
1 answer

Yes, this is a pretty thick thing.

The smart bend here is that hconsSize is recursive, not actually self-relational.

Both apply and hconsSize extend the implicit type Size[X] . There are only two implications that can match this score:

  • hnilSize , but only if X is an HNil type
  • hconsSize

So, apply inserts an hconsSize implicit, which adds 1 to the stack and pulls an implicit hconsSize into another (not necessarily in that order). This continues until we encounter an element of type HNil . Then the implicit hnilSize is pulled in, get is zero, the stack is expanded, and all these 1 add up.

Result: number of elements in a shapeless HList.

+7
source

All Articles