There’s a lot of talks about typelevel things in Scala. Shapeless has gained huge amount of attention lately. There are a lot of cool typelevel tricks out there, coined by Miles Sabin, the type astonaut. Some even say, he does not exist at the runtime. Anyway, I’d like to collect some of those tricks here, for future reference. I’m also doing this to get a better understanding of those tricks.
|Unboxed Tagged Types||Something like Haskell’s newtype, but better.|
|Dependent types||Have types depend on values|
|Unapply||Reduce needed type annotations by guiding scala’s type inference|
|Ambiguous implicits||A way to guarantee that a polymorphic function will not return some specific type|
There’s already a great explanation, including the needed intuition, in Eric Torreborre’s blog. This technique allows for having some typelevel guarantees on the values. Here’s a motivating example. Say, you want to create a function, which operates on positive doubles. Here’s how you could go about this:
def log(i: Double): Option[Double] = if(i > 0) scala.math.log(i) else None
It’s a totally ok way to do this, but imagine, you want several such functions, and you want to...