Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the important features of the shapeless API (in Scala), and what do they do?

I'm trying to learn shapeless (2.0.0). It seems like an amazing tool and I'm very excited about it, but I am having problems moving forward. Because there is not yet much documentation, I've been poring over examples and the source code. I am having difficulties because most examples use multiple shapeless concepts and, in the source code, one shapeless type will often make use of others, so I end up going down the shapeless rabbit hole, so to speak. I think it would be helpful to have a list of the important features of the shapeless API along with a simple description of what each one does. As I'm clearly unqualified to make such a list, I am asking you, the humans of Stack Overflow!

For each feature, please include as much as you can of the following:

  1. The feature's name and how to import it.

  2. A short, simple description of what it does.

  3. Why is this feature important / why would someone bother to use it?

  4. A simple example that uses as few other shapeless or advanced Scala concepts as possible.

By a feature of the API, I mean a single thing (e.g., a type, a function, an object, etc.), or small set of closely coupled such things, that is defined by shapeless 2.0 and can be imported and used in a program. I am not referring to general concepts such as higher order polymorphism or type-level recursion. And please only include one feature per answer. Maybe if there are enough answers and enough others also use this list, we can use the votes on the answers to rank the importance of the different features.

Note: I am aware of this feature list. I think it's great, and it has helped me a lot. However, I'm looking for something more similar to API documentation than a list of things you can do. I can understand many of the examples and infer the purposes of some features from them, but I will often get tripped up on some particular piece and be unable to figure out its function.

like image 838
jcrudy Avatar asked Dec 31 '13 23:12

jcrudy


1 Answers

HList

An HList is a list-like data structure that can hold objects of multiple types. HList is actually a trait. A given HList will have a more specific type that fully specifies the types of its contents. HLists are immutable. The usual way to import HList functionality is via

import shapeless._

HLists are useful when you need an immutable collection of heterogenous objects that isn't a tuple.

HLists are constructed using HNil, which is the empty HList, and the :: operator. The following example shows how to create an HList that counts to "cat":

val hl = 1 :: 2 :: "cat" :: HNil

The type of hl above includes two Int types and a String type. Shapeless includes many useful operations on HLists, which should be the subjects of other answers.

like image 116
jcrudy Avatar answered Sep 21 '22 23:09

jcrudy