Skip to content

Instantly share code, notes, and snippets.

@andresilva
Last active December 19, 2015 20:18
Show Gist options
  • Save andresilva/6012113 to your computer and use it in GitHub Desktop.
Save andresilva/6012113 to your computer and use it in GitHub Desktop.
HList type sizeOf
import shapeless._
trait Size[A] {
def apply(): Int
}
implicit val shortSize = new Size[Short] {
def apply() = 2
}
implicit val intSize = new Size[Int] {
def apply() = 4
}
implicit val doubleSize = new Size[Double] {
def apply() = 8
}
def sizeOf[A](implicit size: Size[A]) = size()
sizeOf[Int] == 4
trait HListTypeSize[L <: HList] {
def apply(): List[Int]
}
implicit object HNilTypeSize extends HListTypeSize[HNil] {
def apply() = Nil
}
implicit def hlistTypeSize[H, T <: HList](implicit size: Size[H], hlistTypeSize: HListTypeSize[T]) =
new HListTypeSize[H :: T] {
def apply() = size() :: hlistTypeSize()
}
def hsizeOf[L <: HList](implicit hlistTypeSize: HListTypeSize[L]): List[Int] = hlistTypeSize()
hsizeOf[Int :: Double :: Short :: Int :: HNil] == List(4, 8, 2, 4)
hsizeOf[Int :: String :: Short :: Int :: HNil] // doesn't compile. there's no implicit Size[String]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment