Last active
December 19, 2015 20:18
-
-
Save andresilva/6012113 to your computer and use it in GitHub Desktop.
HList type sizeOf
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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