Top Related Projects
A boilerplate-free library for loading configuration files
Yet another JSON library for Scala
Quick Overview
Shapeless is a type-level programming library for Scala that provides advanced generic programming capabilities. It enables developers to write highly reusable and type-safe code by leveraging features like heterogeneous lists, polymorphic function values, and generic representations of algebraic data types.
Pros
- Powerful type-level programming capabilities
- Enables writing highly generic and reusable code
- Strong type safety and compile-time checks
- Extensive ecosystem and integration with other Scala libraries
Cons
- Steep learning curve for beginners
- Can lead to increased compilation times
- Complex error messages can be difficult to interpret
- May introduce additional complexity to codebases if not used judiciously
Code Examples
- Creating and using heterogeneous lists (HLists):
import shapeless._
val hlist = 1 :: "hello" :: true :: HNil
val first: Int = hlist.head
val tail: String :: Boolean :: HNil = hlist.tail
- Generic programming with case classes:
import shapeless._
case class Person(name: String, age: Int)
val gen = Generic[Person]
val repr = gen.to(Person("Alice", 30)) // "Alice" :: 30 :: HNil
val person = gen.from("Bob" :: 25 :: HNil) // Person("Bob", 25)
- Polymorphic functions:
import shapeless._
object size extends Poly1 {
implicit def caseInt = at[Int](x => 1)
implicit def caseString = at[String](_.length)
implicit def caseList[T] = at[List[T]](_.size)
}
val result = size(10) :: size("hello") :: size(List(1, 2, 3)) :: HNil
// 1 :: 5 :: 3 :: HNil
Getting Started
To use Shapeless in your Scala project, add the following dependency to your build.sbt file:
libraryDependencies += "com.chuusai" %% "shapeless" % "2.3.10"
Then, import the necessary Shapeless features in your Scala code:
import shapeless._
// Your Shapeless-powered code here
Start by exploring HLists, Generic derivation, and Poly functions to get familiar with Shapeless's core concepts.
Competitor Comparisons
A boilerplate-free library for loading configuration files
Pros of PureConfig
- Focused specifically on configuration management, making it more user-friendly for this use case
- Simpler API and easier learning curve for developers new to the library
- Built-in support for common configuration formats like HOCON, properties files, and JSON
Cons of PureConfig
- Less flexible and powerful for generic programming tasks outside of configuration
- More limited in terms of advanced type-level programming capabilities
- Smaller ecosystem and community compared to Shapeless
Code Comparison
PureConfig:
import pureconfig._
import pureconfig.generic.auto._
case class AppConfig(host: String, port: Int)
val config = ConfigSource.default.load[AppConfig]
Shapeless:
import shapeless._
val gen = Generic[AppConfig]
val repr = gen.to(AppConfig("localhost", 8080))
val config = gen.from(repr)
While both libraries can handle case class transformations, PureConfig is more focused on configuration loading, whereas Shapeless provides a more general-purpose approach to generic programming in Scala.
Yet another JSON library for Scala
Pros of circe
- Focused specifically on JSON encoding/decoding, making it more user-friendly for this common task
- Provides automatic derivation of encoders and decoders for case classes and sealed traits
- Offers better performance for JSON processing compared to more general-purpose libraries
Cons of circe
- Limited to JSON processing, whereas Shapeless is a more versatile generic programming library
- May have a steeper learning curve for users unfamiliar with type-level programming concepts
- Less flexibility for advanced type manipulations compared to Shapeless
Code Comparison
circe example:
import io.circe._, io.circe.generic.auto._, io.circe.parser._, io.circe.syntax._
case class Person(name: String, age: Int)
val json = Person("Alice", 30).asJson
val decodedPerson = json.as[Person]
Shapeless example:
import shapeless._
case class Person(name: String, age: Int)
val generic = Generic[Person]
val repr = generic.to(Person("Alice", 30))
val person = generic.from(repr)
Both libraries leverage compile-time code generation, but circe focuses on JSON processing while Shapeless provides more general-purpose generic programming capabilities. circe is easier to use for JSON tasks, while Shapeless offers greater flexibility for complex type-level operations.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
shapeless: generic programming for Scala
shapeless is a type class and dependent type based generic programming library for Scala. It had its origins in several talks by Miles Sabin (@milessabin), given over the course of 2011, on implementing scrap your boilerplate and higher rank polymorphism in Scala. Since then it has evolved from being a resolutely experimental project into a library which, while still testing the limits of what's possible in Scala, is being used widely in production systems wherever there are arities to be abstracted over and boilerplate to be scrapped.
Projects which use shapeless
There is a wide variety of projects which use shapeless in one way or another ... see the incomplete list of projects for ideas and inspiration. If you are using shapeless and your project isn't listed yet, please add it.
Finding out more about the project
The feature overview for shapeless-2.0.0 provides a very incomplete introduction to shapeless. Additional information can be found in subsequent release notes. If you are upgrading from shapeless-2.0.0 you will find the migration guide useful. We're not satisfied with the current state of the documentation and would love help in improving it. You can find an excellent guide to Shapeless here: The Type Astronaut's Guide to Shapeless.
shapeless is part of the Typelevel family of projects. It is an Open Source project under the Apache License v2, hosted on github. Binary artefacts are published to the Sonatype OSS Repository Hosting service and synced to Maven Central.
Most discussion of shapeless and generic programming in Scala happens on the #shapless channel of the Typelevel Discord. There is also a mailing list and Gitter, but these are largely dormant now that most activity has moved to Discord. Questions about shapeless are often asked and answered under the shapeless tag on StackOverflow. Some articles on the implementation techniques can be found on Miles's blog, and Olivera, Moors and Odersky, Type Classes as Object and Implicits is useful background material.
Participation
The shapeless project supports the Typelevel Code of Conduct and wants all of its channels (mailing list, Gitter, IRC, github, etc.) to be welcoming environments for everyone.
Whilst shapeless is a somewhat "advanced" Scala library, it is a lot more approachable than many people think. Contributors are usually available to field questions, give advice and discuss ideas on the #shapeless Discord channel, and for people wanting to take their first steps at contributing we have a selection of open issues flagged up as being good candidates to take on. No contribution is too small, and guidance is always available.
Using shapeless
Binary release artefacts are published to the Sonatype OSS Repository Hosting service and synced to Maven Central. Snapshots of the main branch are built using GitHub actions and automatically published to the Sonatype OSS Snapshot repository.
Try shapeless with an Ammonite instant REPL
The quickest way to get to a REPL prompt with the latest version of shapeless on the class path is to run the provided "try shapeless" script, which has no dependencies other than an installed JDK. This script downloads and installs coursier and uses it to fetch the Ammonite REPL and the latest version of shapeless. It then drops you immediately into a REPL session,
% curl -s https://raw.githubusercontent.com/milessabin/shapeless/main/scripts/try-shapeless.sh | bash
Loading...
Compiling (synthetic)/ammonite/predef/interpBridge.sc
Compiling (synthetic)/ammonite/predef/replBridge.sc
Compiling (synthetic)/ammonite/predef/DefaultPredef.sc
Compiling /home/miles/projects/shapeless/(console)
Welcome to the Ammonite Repl 1.6.8
(Scala 2.13.1 Java 1.8.0_212)
If you like Ammonite, please support our development at www.patreon.com/lihaoyi
@ 23 :: "foo" :: true :: HNil
res0: Int :: String :: Boolean :: HNil = 23 :: "foo" :: true :: HNil
@ Bye!
%
shapeless-2.3.3 with SBT
To include the Sonatype repositories in your SBT build you should add,
resolvers ++= Seq(
Resolver.sonatypeRepo("releases"),
Resolver.sonatypeRepo("snapshots")
)
Builds are available for Scala 2.11.x, 2.12.x and 2.13.x. The main line of development for shapeless 2.3.3 is Scala 2.13.2.
scalaVersion := "2.13.5"
libraryDependencies ++= Seq(
"com.chuusai" %% "shapeless" % "2.3.3"
)
For using snapshots of Shapeless you should add,
scalaVersion := "2.13.5"
libraryDependencies ++= Seq(
"com.chuusai" %% "shapeless" % "2.4.0-SNAPSHOT"
)
shapeless-2.3.3 with Maven
shapeless is also available for projects using the Maven build tool via the following dependency,
<dependency>
<groupId>com.chuusai</groupId>
<artifactId>shapeless_2.13</artifactId>
<version>2.3.3</version>
</dependency>
Older releases
Please use a current release if possible. If unavoidable, you can find usage information for older releases on the shapeless wiki.
Building shapeless
shapeless is built with SBT 1.3.10 or later, and its main branch is built with Scala 2.13.2 by default but also cross-builds for 2.11.12 and 2.12.12.
Contributors
- Alex Zorab alec.zorab@gmail.com @aleczorab
- Alessandro Lacava alessandrolacava@gmail.com @lambdista
- Alexander Konovalov alex.knvl@gmail.com @alexknvl
- Alexandre Archambault alexandre.archambault@gmail.com @alxarchambault
- Alistair Johnson alistair.johnson@johnsonusm.com @AlistairUSM
- Allison H. allisonhb@gmx.com
- Alois Cochard alois.cochard@gmail.com @aloiscochard
- Andreas Koestler andreas.koestler@gmail.com @AndreasKostler
- Andrew Brett github@bretts.org @Ephemerix
- Aristotelis Dossas teldosas@gmail.com @teldosas
- Arya Irani arya.irani@gmail.com @aryairani
- Ben Hutchison brhutchison@gmail.com @ben_hutchison
- Ben James ben.james@guardian.co.uk @bmjames
- Brian McKenna brian@brianmckenna.org @puffnfresh
- Brian Zeligson brian.zeligson@gmail.com @beezee
- Bryn Keller xoltar@xoltar.org @brynkeller
- Carlos Quiroz @carlosmquiroz
- Chris Hodapp clhodapp1@gmail.com @clhodapp
- Cody Allen ceedubs@gmail.com @fourierstrick
- Dale Wijnand dale.wijnand@gmail.com @dwijnand
- Daniel Urban urban.dani@gmail.com
- Dario Rexin dario.rexin@r3-tech.de @evonox
- Dave Gurnell d.j.gurnell@gmail.com @davegurnell
- David Barri japgolly@gmail.com @japgolly
- Denis Mikhaylov notxcain@gmail.com @notxcain
- Dmitry Kovalev kdn.kovalev@gmail.com
- Eugene Burmako xeno.by@gmail.com @xeno_by
- Fabio Labella fabio.labella2@gmail.com @SystemFw
- Filipe Nepomuceno filinep@gmail.com
- Frank S. Thomas frank@timepit.eu @fst9000
- George Leontiev folone@gmail.com @folone
- Georgi Krastev joro.kr.21@gmail.com @Joro_Kr
- Hamish Dickenson hamish.dickson@gmail.com @hamishdickson
- Harrison Houghton hhoughton@learningobjects.com
- Howard Branch purestgreen@gmail.com @purestgreen
- Huw Giddens hgiddens@gmail.com
- Hywel Andrews hywel.andrews@agoda.com
- Ievgen Garkusha ievgen@riskident.com
- Jacob Barber jacoby6000@gmail.com @jacoby6000
- Jason Zaugg jzaugg@gmail.com @retronym
- Jean-Baptiste Giraudeau jb@giraudeau.info @jb9i
- Jean-Remi Desjardins jeanremi.desjardins@gmail.com @jrdesjardins
- Jeff Martin jmartin@homeaway.com
- Jeff Wilde jeff@robo.ai
- Jeremy R. Smith jeremyrsmith@gmail.com @jeremyrsmith
- Jisoo Park xxxyel@gmail.com @guersam
- Johannes Rudolph johannes.rudolph@gmail.com @virtualvoid
- Johnny Everson khronnuz@gmail.com @johnny_everson
- Jolse Maginnis jolse.maginnis@pearson.com @doolse2
- Joni Freeman joni.freeman@ri.fi @jonifreeman
- Joseph Price josephprice@iheartmedia.com
- Juan José Vázquez Delgado juanjo.vazquez.delgado@tecsisa.com @juanjovazquez
- Julien Tournay boudhevil@gmail.com @skaalf
- Jules Gosnell jules_gosnell@yahoo.com
- Kailuo Wang kailuo.wang@gmail.com @kailuowang
- Kazuki Moriyama pharcydetip@gmail.com @kazchimo
- Kenji Yoshida 6b656e6a69@gmail.com @xuwei_k
- Kevin Wright kev.lee.wright@gmail.com @thecoda
- Lars Hupel lars.hupel@mytum.de @larsr_h
- Lukasz Golebiewski lukasz.golebiewski@gmail.com @LukaszGobiewsk1
- Mario Pastorelli mario.pastorelli@teralytics.ch @mapastr
- Matthew Taylor matthew.t@tbfe.net
- Mathias Doenitz mathias@spray.io @sirthias
- Michael Donaghy md401@srcf.ucam.org
- Michael Pilquist mpilquist@gmail.com @mpilquist
- Michael Zuber michaelg.zuber@gmail.com @mgzuber91
- Mike Limansky mike.limansky@gmail.com @mike_limansky
- Miles Sabin miles@milessabin.com @milessabin
- n4to4 n4to4k@gmail.com @n4to4
- Neville Li neville@spotify.com @sinisa_lyh
- Nikolas Evangelopoulos nikolas@jkl.gr
- Oleg Aleshko olegych@tut.by @OlegYch
- Olivier Blanvillain olivier.blanvillain@gmail.com
- Olli Helenius liff@iki.fi @ollijh
- Owein Reese owreese@gmail.com @OweinReese
- Paolo G. Giarrusso p.giarrusso@gmail.com @blaisorblade
- Pascal Voitot pascal.voitot.dev@gmail.com @mandubian
- Pavel Chlupacek pavel.chlupacek@spinoco.com @pacmanius
- Peter Neyens peter.neyens@gmail.com @pneyens
- Peter Schmitz petrischmitz@gmail.com @peterschmitz_
- Renato Cavalcanti renato@strongtyped.io @renatocaval
- Rob Norris rob_norris@mac.com @tpolecat
- Robert Hensing spam@roberthensing.nl
- Ronan Michaux ronan_michaux@yahoo.com @ronan_michaux
- Ryadh Khsib ryadh.khsib@gmail.com
- Ryo Hongo ryoppy0516@gmail.com @ryoppy516
- Sam Halliday sam.halliday@gmail.com @fommil
- Sarah Gerweck sarah.a180@gmail.com @SGerweck
- Sébastien Doeraene sjrdoeraene@gmail.com @sjrdoeraene
- Simon Hafner hafnersimon@gmail.com @reactormonk
- Stacy Curl stacy.curl@gmail.com @stacycurl
- Stanislav Savulchik s.savulchik@gmail.com @savulchik
- Stephen Compall scompall@nocandysw.com @S11001001
- Tin Pavlinic tin.pavlinic@gmail.com @triggerNZ
- Tom Switzer thomas.switzer@gmail.com @tixxit
- Tomas Mikula tomas.mikula@gmail.com @tomas_mikula
- Travis Brown travisrobertbrown@gmail.com @travisbrown
- Valentin Kasas valentin.kasas@gmail.com @ValentinKasas
- Valerian Barbot valerian.barbot@onzo.com @etaty
- Valy Diarrassouba v.diarrassouba@gmail.com
- Vladimir Matveev vladimir.matweev@gmail.com @netvlm
- Vladimir Pavkin vpavkin@gmail.com @vlpavkin
- William Harvey harveywi@cse.ohio-state.edu
- Yang Bo (æ¨å) pop.atry@gmail.com @Atry
- Zainab Ali zainab.ali.london@gmail.com @zainabali
Top Related Projects
A boilerplate-free library for loading configuration files
Yet another JSON library for Scala
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot