Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Who can explain the meaning of this scala code

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.

like image 974
Knows Not Much Avatar asked Jun 08 '16 04:06

Knows Not Much


People also ask

Who is the developer of Scala programming language?

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 explain?

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.

What is a Scala code?

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).

How does Scala code work?

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.


1 Answers

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:

  1. hnilSize, but only if X is type HNil
  2. hconsSize itself

So 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.

like image 124
jwvh Avatar answered Oct 21 '22 21:10

jwvh