{"id":18753048,"url":"https://github.com/spotify/dataenum","last_synced_at":"2025-04-09T20:10:54.435Z","repository":{"id":57727186,"uuid":"114262958","full_name":"spotify/dataenum","owner":"spotify","description":"Algebraic data types in Java.","archived":false,"fork":false,"pushed_at":"2023-10-13T11:15:35.000Z","size":233,"stargazers_count":168,"open_issues_count":5,"forks_count":16,"subscribers_count":15,"default_branch":"master","last_synced_at":"2025-04-09T20:10:49.029Z","etag":null,"topics":["algebraic-data-types","java"],"latest_commit_sha":null,"homepage":"","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/spotify.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-12-14T14:55:41.000Z","updated_at":"2025-03-10T06:05:16.000Z","dependencies_parsed_at":"2025-03-03T08:10:16.452Z","dependency_job_id":"7c3b78c2-e9ff-4a02-9c41-bdd27fccc119","html_url":"https://github.com/spotify/dataenum","commit_stats":null,"previous_names":[],"tags_count":10,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spotify%2Fdataenum","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spotify%2Fdataenum/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spotify%2Fdataenum/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spotify%2Fdataenum/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/spotify","download_url":"https://codeload.github.com/spotify/dataenum/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248103872,"owners_count":21048245,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["algebraic-data-types","java"],"created_at":"2024-11-07T17:23:59.837Z","updated_at":"2025-04-09T20:10:54.406Z","avatar_url":"https://github.com/spotify.png","language":"Java","readme":"[![Build Status](https://travis-ci.org/spotify/dataenum.svg?branch=master)](https://travis-ci.org/spotify/dataenum)\n[![codecov](https://codecov.io/gh/spotify/dataenum/branch/master/graph/badge.svg)](https://codecov.io/gh/spotify/dataenum)\n[![Maven Central](https://img.shields.io/maven-central/v/com.spotify.dataenum/dataenum.svg)](https://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.spotify.dataenum%22%20dataenum*)\n[![License](https://img.shields.io/github/license/spotify/dataenum.svg)](LICENSE)\n\n# DataEnum\n\nDataEnum allows you to work with [algebraic data types](https://en.wikipedia.org/wiki/Algebraic_data_type) in Java.\n\nYou can think of it as an enum where every individual value can have different data associated with it.\n\n## What problem does it solve?\n\nThe idea of algebraic data types is not new and already exists in many other programming languages, for example:\n\n- [Sealed classes](https://kotlinlang.org/docs/reference/sealed-classes.html) in Kotlin\n- [Enumerations with associated values](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Enumerations.html) in Swift\n- [Case classes](https://docs.scala-lang.org/tour/case-classes.html) in Scala\n- [Data types](https://wiki.haskell.org/Algebraic_data_type) in Haskell\n\nIt is possible to represent such algebraic data types using subclasses: the parent class is the \"enumeration\"\ntype, and each child class represents a case of the enumeration with it's associated parameters. This will however\neither require you to spread out your business logic in all the subclasses, or to cast the child class manually to\naccess the parameters and be very careful to only cast if you know for sure that the class is of the right type. \n\nThe goal of DataEnum is to help you generate all these classes and give you a fluent API for easily accessing their data\nin a type-safe manner.\n\nThe primary use-case we had when designing DataEnum was to execute different business logic depending on an incoming\nmessage. And as mentioned above, we wanted to keep all that business logic in one place, and not spread it out in\ndifferent classes. With plain Java, you’d have to write something like this:\n\n```java\nif (message instanceof Login) {\n    Login login = (Login) message;\n    // login logic here\n} else if (message instanceof Logout) {\n    Logout logout = (Logout) message;\n    // logout logic here\n}\n```\n\nThere are a number of things here that developers tend to not like: repeated if-else statements, manual `instanceof`\nchecks and safe-but-noisy typecasting. On top of that it doesn't look very idiomatic and there's a high risk that\nmistakes get introduced over time. If you use DataEnum, you can instead write the same expression like this:\n\n```java\nmessage.match(\n   login -\u003e { /* login logic; the 'login' parameter is 'message' but cast to the type Login. */ },\n   logout -\u003e { /* logout logic; the 'logout' parameter is 'message' but cast to the type Logout. */ }\n);\n```\n\nIn this example only one of the two lambdas will be executed depending on the message type, just like with the\nif-statements. `match` is just a method that takes functions as arguments, but if you write expressions with linebreaks\nlike in the example above it looks quite similar to a switch-statement, a match-expression in Scala, or a\nwhen-expression in Kotlin. DataEnum makes use of this similarity to make match-statements look and feel like a\nlanguage construct.\n\nThere are many compelling use-cases for using an algebraic data type to represent values. To name a few:\n\n- **Create a vocabulary of possible actions**. List all the actions that can be performed in a certain part of your \n  application, for example on a login/logout page. Each action can have different data associated with it, for example\n  the login action would have a username and password, while a logout action doesn't have any data.\n\n- **Representing states of a state machine**. This allows you to only keep the data that actually is available in each\n  state, making it impossible to even reference data that isn't available in a particular state.\n\n- **Rich, type-safe error handling** Instead of having just an error code as a result of a network request, you can\n  have different types for different errors, each with relevant information attached: `ConnectivityLost`,\n  `NoRouteToHost(String host)`, `TooManyRetries(int retryCount)`.\n\n- **Metadata in RxJava streams**. It is often useful to wrap data in RxJava in order to provide metadata about what's\n  happening. One common example is to represent different kinds of success and failure: `InProgress(T placeholder)`,\n  `Success(T data)`, `Error(String reason)`.\n \n## Status\n\nDataEnum is in Beta status, meaning it is used in production in Spotify Android applications, but\nwe may keep making changes relatively quickly.\n\nIt is currently built for Java 7 (because Android doesn't support Java 8 well yet), hence the\nduplication of some concepts defined in `java.util.function` (`Consumer`, `Function`, `Supplier`).\n\n## Using it in your project\n\nThe latest version of DataEnum is available through Maven Central (LATEST_RELEASE below is ![latest not found](https://img.shields.io/maven-central/v/com.spotify.dataenum/dataenum.svg)):\n\n#### Gradle\n\n```\nimplementation 'com.spotify.dataenum:dataenum:LATEST_RELEASE'                \nannotationProcessor 'com.spotify.dataenum:dataenum-processor:LATEST_RELEASE' \n```\n\n#### Maven\n\n```xml\n\u003cdependencies\u003e\n  \u003cdependency\u003e\n    \u003cgroupId\u003ecom.spotify.dataenum\u003c/groupId\u003e\n    \u003cartifactId\u003edataenum\u003c/artifactId\u003e\n    \u003cversion\u003eLATEST_RELEASE\u003c/version\u003e\n  \u003c/dependency\u003e\n  \u003cdependency\u003e\n    \u003cgroupId\u003ecom.spotify.dataenum\u003c/groupId\u003e\n    \u003cartifactId\u003edataenum-processor\u003c/artifactId\u003e\n    \u003cversion\u003eLATEST_RELEASE\u003c/version\u003e\n    \u003cscope\u003eprovided\u003c/scope\u003e\n  \u003c/dependency\u003e\n\u003c/dependencies\u003e\n```\n\nIt may be an option to use the [annotationProcessorPaths](https://maven.apache.org/plugins/maven-compiler-plugin/compile-mojo.html#annotationProcessorPaths)\nconfiguration option of the maven-compiler-plugin rather than an optional dependency.\n\n## How do I create a DataEnum type?\nFirst, you define all the cases and their parameters in an interface like this:\n\n```java\n@DataEnum\ninterface MyMessages_dataenum {\n    dataenum_case Login(String userName, String password);\n    dataenum_case Logout();\n    dataenum_case ResetPassword(String userName);\n}\n```\n\nThen, you apply the `dataenum-processor` annotation processor to that code, and your DataEnum case \nclasses will be generated for you.\n\nSome things to note:\n\n- We use a Java interface for the specification. The rationale is that it allows the IDE to help you find\n  and import types correctly. We deliberately made it look weird, so nobody would think it’s a normal class.\n  This is abusing Java a bit, but we’re OK with that.\n\n- The interface will never be used for anything other than code generation, so you should normally \n  make the interface package-private. The one exception is when one `_dataenum` spec needs to\n  reference another as described below.\n\n- The interface name has to end with `_dataenum`. This is to make the interface stick out and make\n  it easier to filter out from artifacts and exclude from static analysis.\n\n- The methods in the interface have to be declared as returning a `dataenum_case`. Each method\n  corresponds to one of the possible cases of the enum, and the parameters of the method become the\n  member fields of that case. Note that the method names from the interface will be used as class names\n  for the cases, so you'll want to name them using CamelCase as in the example above. The methods\n  in the `_dataenum` interface will never be implemented, and there is no way to create a `dataenum_case` \n  instance. The type is only used as a marker.\n\n- The prefix of the `@DataEnum` annotated interface will be used as the name of a generated super-class\n  (`MyMessages` in the example above). This class will have factory methods for all the cases.\n\n- For each method in the interface, an inner class will be generated (in this example `MyMessages.Login`,\n  `MyMessages.Logout` and `MyMessages.ResetPassword`). These classes will extend the outer class `MyMessages`.\n\n## Using the generated DataEnum class\nSome usage examples, based on the `@DataEnum` specification above:\n\n```java\n// Instantiate by passing in the required parameters. \n// You’ll get something that is of the super type - this is to help Java’s \n// not-always-great type inference do the right thing in many common cases.\nMyMessages message = MyMessages.login(\"petter\", \"s3cr3t\");\n\n// If you actually needed the subtype you can easily cast it using the as-methods.\nLogout logout = MyMessages.logout().asLogout();\n\n// For every as-method there is also an is-method to check the type of the message.\nassertThat(message.isLogin(), is(true));\n\n// Apply different business logic to different message types. Note how getters are generated (but not\n// setters, DataEnum case types should be considered immutable).\nmessage.match(\n    login -\u003e Logger.debug(\"got a login request from user: {}\", login.userName()),\n    logout -\u003e Logger.debug(\"user logged out\"),\n    resetPassword -\u003e Logger.debug(\"password reset requested for user: {}\", resetPassword.userName())\n);\n\n// So far we've been looking at 'match', but there is also the very useful 'map' which is used to\n// transform values. When using 'map' you define how the message should be transformed in each case.\nint passwordLength = message.map(\n    login -\u003e login.password().length(),\n    logout -\u003e 0,\n    resetPassword -\u003e -1);\n}\n\n// There are some utility methods provided that allow you to deal with unimplemented or illegal cases:\nint passwordLength = message.map(\n    login -\u003e login.password().length(),\n    logout -\u003e Cases.illegal(\"logout message does not contain a password\"), // throws IllegalStateException\n    resetPassword -\u003e Cases.todo()); // throws UnsupportedOperationException\n}\n\n// Sometimes, only a minority of cases are handled differently, in which case a 'map' or 'match'\n// can lead to duplication:\nint passwordLength = message.map(\n    login -\u003e handleLogin(login),\n    logout -\u003e Cases.illegal(\"only login is allowed\"),\n    resetPassword -\u003e Cases.illegal(\"only login is allowed\")\n    // This could really get bad if there are many cases here\n);\n\n// For those scenarios you can just use regular language control structures (like if-else):\nif (message.isLogin()) {\n  return handleLogin(message.asLogin()); // Technically just a cast but easier to read than manual casting.\n} else {\n  throw new IllegalStateException(\"only login is allowed\");\n}\n```\n\n## Features\n\n- Case types are immutable. All generated classes are value types and cannot be modified after being created. Of course\n  this assumes that all the parameters of your cases are immutable too, since an object only is immutable if all its\n  fields also are immutable.\n- Everything is non-null by default. Passing in a null will cause an exception to be thrown unless you explicitly\n  annotate the parameters as `@Nullable`. Any annotation with the name 'Nullable' can be used.\n- `toString`, `hashCode`, and `equals` are generated for all case classes.\n- isFoo/asFoo methods are provided, as a more high level alternative to manually doing `instanceof` and casting.\n- Generic type support. The DataEnum interfaces can be type parameterized, which makes it possible to create reusable\n  data types. \n- Recursive data type support. The generated DataEnum types may refer to itself recursively, even with type parameters.\n  When doing so you must use the `_dataenum`-suffixed name to avoid any chicken-and-egg problems with the generated\n  classes.\n  \n  The recursive data type support allows you to do things like this:\n  \n  ```java\n  @DataEnum\n  interface Tree_dataenum\u003cT\u003e {\n    dataenum_case Branch(Tree_dataenum\u003cT\u003e left, Tree_dataenum\u003cT\u003e right);\n    dataenum_case Leaf(T value);\n  }\n  ```\n- Sometimes, you want to reference a dataenum from another one. You can do that using this slightly\n  clunky syntax:\n\n  ```java\n  interface First_dataenum {\n    dataenum_case SomeCase();\n  }\n\n  interface Second_dataenum {\n    dataenum_case NeedsFirst(First_dataenum first);\n  }\n  ```\n  The generated `NeedsFirst` class will have a member field that is of the type `First`. Again, because\n  the `First` class doesn't exist until the annotation processor has run, so the `Second_dataenum` spec\n  must reference the `First_dataenum` spec. If `First_dataenum` is in a different package than\n  `Second_dataenum`, it must of course be public.\n- If you have sensitive information in a field and don't want the generated `toString` method to \n  print that information, you can use the `@Redacted` annotation:\n  ```java\n  dataenum_case UserInfo(String name, @Redacted String password);\n  ```    \n  We provide an annotation in the runtime dependencies, but any annotation named `Redacted` will work.\n\n## Configuration\n\nDataEnum currently has a single configurable setting determining the visibility of constructors in\ngenerated code. Generally speaking, `private` is best as it ensures there is a single way of creating\ncase instances (the generated static factory methods like `MyMessages.login(String, String)` above).\nHowever, for Android development, you want to keep the method count down to a minimum, and private\nconstructors lead to synthetic constructors being generated, increasing the method count. Since that\nis an important use case for us, we've chosen the package-private as the default. This is configurable\nthrough adding a\n[`@ConstructorAccess`](https://javadoc.io/page/com.spotify.dataenum/dataenum/latest/com/spotify/dataenum/ConstructorAccess.html)\nannotation to a `package-info.java` file. See the javadocs for more information.\n\n## Known weaknesses of DataEnum\n\n- While the generated classes are immutable, they do not enforce that parameters are immutable. It is up to users of\n  DataEnum to eg. use ImmutableList for lists instead of List.\n\n- The names of the arguments to the lambdas when using `match`/`map` only indicate the type of the object by convention,\n  so some discipline is required to make sure you manually update lambda argument names if a case is renamed.\n\n- Renaming cases of a dataenum can be painful since the generated class doesn't have a connection to the interface. \n\n- Reordering cases can be dangerous if you only use lambdas with type-inference. If you swap the order of two cases\n  with the same parameter names then usages of `map`/`match` will still compile even though they are now incorrect.\n  This can be mitigated using method references instead of lambdas, lambdas with explicit type parameters, and good test\n  coverage of code using DataEnum.\n\n- The `_dataenum`-suffixed interface is only used as an input to code generation, and it breaks certain conventions\n  around naming. You might need to suppress some static analysis when you use DataEnum, and you probably want to strip\n  the `_dataenum` classes from artifacts.\n\n## Alternatives\n  \nAn alternative implementation of algebraic data types for Java is [ADT4J](https://github.com/sviperll/adt4j). We feel\nDataEnum has the advantage of being less verbose than ADT4J, although ADT4J is more flexible in terms of customising\nyour generated types.\n\n## Features that might be added in the future\n\n- Generating builders for case types with many parameters.\n- Generating mutator functions for case types to create modified versions of them.\n- Support for writing extensions, eg. to allow adding support for serialization.\n- IntelliJ plugin for refactoring and for generating map/match statements.\n\n## Why is it called DataEnum?\nThe name ‘DataEnum’ comes from the fact that it’s used similarly to an enum, but you can easily and type-safely have\ndifferent data attached to each enum value.\n\n## Code of Conduct\n\nThis project adheres to the [Open Code of Conduct][code-of-conduct]. By participating, you are expected to honor this code.\n\n[code-of-conduct]: https://github.com/spotify/code-of-conduct/blob/master/code-of-conduct.md\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspotify%2Fdataenum","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fspotify%2Fdataenum","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspotify%2Fdataenum/lists"}