I am reading this code for a long time. I typed it into REPL and it works as well.
but I don't have any idea of what's going on here. Why and how does this even 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 going on here.
The design of Scala started in 2001 at the École Polytechnique Fédérale de Lausanne (EPFL) (in Lausanne, Switzerland) by Martin Odersky. It followed on from work on Funnel, a programming language combining ideas from functional programming and Petri nets.
What is Scala? Scala is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It seamlessly integrates features of object-oriented and functional languages.
Scala stands for Scalable Language. It is a multi-paradigm programming language. Scala language includes features of functional programming and object-oriented programming. It is a statically typed language. Its source code is compiled into bytecode and executed by Java virtual machine(JVM).
Scala compiles the code using scala compiler and converts code into Java Byte Code and Executes it on JVM. These were the Features of Scala and let us get into few of the frameworks of Scala is capable to support.
Yeah, that's pretty thick stuff.
The mind-bender here is that hconsSize
is recursive without actually being self referential.
Both apply
and hconsSize
pull in an implicit of type Size[X]
. There are only two implicits that could fit that bill:
hnilSize
, but only if X
is type HNil
hconsSize
itselfSo apply
pulls in the hconsSize
implicit, which adds 1 to the stack and pulls in another hconsSize
implicit (not necessarily in that order). This continues until we encounter an element of type HNil
. Then the hnilSize
implicit is pulled in, the get
is zero, the stack is unrolled and all those 1's are added up.
Result: number of elements in the shapeless HList.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With