You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
* Make data classes public, deprecate old extension constructor and add new one
* Update docs
* Use camelcase class names for function names
* Deprecate coproductOf as well
* First pass at runnable docs
* First pass at kdocs
* Add test for type inference with ADT
* Add example of how Coproducts can flatten hierarchies
* Move Constructors to top level section since it's no longer an extension function
* Update to use @param and @return for kdocs so the docs get generated correctly
* Add String Util method and update docs
@@ -24,8 +19,13 @@ class CoproductTest : UnitSpec() {
24
19
init {
25
20
26
21
"Coproducts should be generated up to 22" {
27
-
classProof2(f:Coproduct2<Unit, Unit>) { val x = f }
28
-
classProof22(f:Coproduct22<Unit, Unit, Unit, Unit, Unit, Unit, Unit, Unit, Unit, Unit, Unit, Unit, Unit, Unit, Unit, Unit, Unit, Unit, Unit, Unit, Unit, Unit>) { val x = f }
22
+
classProof2(f:Coproduct2<Unit, Unit>) {
23
+
val x = f
24
+
}
25
+
26
+
classProof22(f:Coproduct22<Unit, Unit, Unit, Unit, Unit, Unit, Unit, Unit, Unit, Unit, Unit, Unit, Unit, Unit, Unit, Unit, Unit, Unit, Unit, Unit, Unit, Unit>) {
27
+
val x = f
28
+
}
29
29
}
30
30
31
31
"select should return None if value isn't correct type" {
@@ -82,5 +82,49 @@ class CoproductTest : UnitSpec() {
Coproducts represent a sealed hierarchy of types where only one of the specified set of types exist every time. Conceptually, it's very similar to the stdlib `sealed` class, or to [Either]({{ '/docs/arrow/core/either' | relative_url }}) if we move on to Arrow data types. [Either]({{ '/docs/arrow/core/either' | relative_url }}) supports one of two values, an `Either<A, B>` has to contain an instance of `A` or `B`. We can extrapolate that concept to `N` number of types. So a `Coproduct5<A, B, C, D, E>` has to contain an instance of `A`, `B`, `C`, `D`, or `E`. For example, perhaps there's a search function for a Car Dealer app that can show `Dealership`s, `Car`s and `SalesPerson`s in a list, we could model that list of results as `List<Coproduct3<Dealership, Car, SalesPerson>`. The result would contain a list of heterogeneous elements but each element is one of `Dealership`, `Car` or `SalesPerson` and our UI can render the list elements based on those types.
25
25
26
-
```kotlin:ank
26
+
```kotlin:ank:playground
27
27
import arrow.generic.*
28
-
import arrow.generic.coproduct3.Coproduct3
29
-
import arrow.generic.coproduct3.fold
28
+
import arrow.generic.coproduct3.*
30
29
31
30
fun toDisplayValues(items: List<Coproduct3<Car, Dealership, Salesperson>>): List<String> {
32
31
return items.map {
@@ -37,6 +36,18 @@ fun toDisplayValues(items: List<Coproduct3<Car, Dealership, Salesperson>>): List
37
36
)
38
37
}
39
38
}
39
+
40
+
fun main() {
41
+
println(
42
+
toDisplayValues(
43
+
listOf<Coproduct3<Car, Dealership, Salesperson>>(
44
+
Car(Speed(100)).first(),
45
+
Dealership("Cedar Falls, Iowa").second(),
46
+
Salesperson("Car McCarface").third()
47
+
)
48
+
)
49
+
)
50
+
}
40
51
```
41
52
42
53
Let's say we have an api. Our api operates under the following conditions:
@@ -45,73 +56,122 @@ Let's say we have an api. Our api operates under the following conditions:
45
56
46
57
Because we have some common errors that every endpoint can return to us, we can define a sealed class of these and call them `CommonServerError` because they make sense to be sealed together for reusability. Likewise, we can logically group our specific errors into `RegistrationError` and we have `Registration` as our success type.
47
58
48
-
With Coproducts, we're able to define a result for this api call as `Coproduct3<CommonServerError, RegistrationError, Registration>`. We've been able to compose these results without having to write our own sealed class containing all the common errors for each endpoint.
59
+
The most obvious approach would be to use Kotlin's `sealed class`to create a return type for this api call:
49
60
50
-
#### Extensions
61
+
```kotlin:ank
62
+
sealed class ApiResult {
63
+
data class CommonServerError(val value: CommonServerError): ApiResult()
64
+
data class RegistrationError(val value: RegistrationError): ApiResult()
65
+
data class Registration(val value: Registration): ApiResult()
66
+
}
67
+
```
51
68
52
-
##### coproductOf
69
+
Immediately we can observe there's boilerplate to this approach. We need to make a data class that just holds a single value to combine these results to a common type. Any time we need to add to ApiResult we need to go through and add another wrapping class to conform it to this type.
53
70
54
-
So now that we've got our api response modeled, we need to be able to create an instance of `Coproduct3`.
71
+
Upon using it we can also observe that there's unwrapping that needs to take place to actually use the values:
55
72
56
73
```kotlin:ank
74
+
fun handleResult(apiResult: ApiResult): String {
75
+
return when (apiResult) {
76
+
is ApiResult.CommonServerError -> "Common: ${apiResult.value}"
77
+
is ApiResult.RegistrationError -> "RegistrationError: ${apiResult.value}"
78
+
is ApiResult.Registration -> "Registration: ${apiResult.value}"
79
+
}
80
+
}
81
+
```
82
+
83
+
With Coproducts, we're able to define a result for this api call as `typealias ApiResult = Coproduct3<CommonServerError, RegistrationError, Registration>`. We've been able to compose these results without having to write our own sealed class containing all the common errors for each endpoint. This lets us flatten a layer of boilerplate by abstracting the sealed hierarchy and lets us freely compose types from different domain types.
84
+
85
+
#### Constructors
86
+
87
+
So now that we've got our api response modeled, we need to be able to create an instance of `Coproduct3`.
88
+
89
+
```kotlin:ank:playground
57
90
import arrow.generic.*
58
-
import arrow.generic.coproduct3.coproductOf
91
+
import arrow.generic.coproduct3.First
92
+
59
93
60
-
val apiResult = coproductOf<CommonServerError, RegistrationError, Registration>(ServerError) //Returns Coproduct3<CommonServerError, RegistrationError, Registration>
There are `coproductOf` constructor functions for each Coproduct regardless of the arity (number of types). All we have to do is pass in our value and have the correct type parameters on it, the value must be a type declared on the function call.
103
+
Coproducts are backed by a sealed class hierarchy and we can use the data classes to create Coproducts. The class names resemble the index of the generic, for example, Coproduct3<A, B, C> has First, Second and Third. First references the `A`, Second references the `B` and so forth.
64
104
65
105
If we pass in a value that doesn't correspond to any types on the Coproduct, it won't compile:
You might be saying "That's great and all but passing in values as parameters is so Java, I want something more Kotlin!". Well look no further, just like [Either]({{ '/docs/arrow/core/either' | relative_url }})'s `left()` and `right()` extension methods, Coproducts can be created with an extension method on any type:
78
125
79
-
```kotlin:ank
126
+
```kotlin:ank:playground
80
127
import arrow.generic.*
81
-
import arrow.generic.coproduct3.cop
128
+
import arrow.generic.coproduct3.*
82
129
83
-
val apiResult = ServerError.cop<CommonServerError, RegistrationError, Registration>() //Returns Coproduct3<CommonServerError, RegistrationError, Registration>
All we have to do is provide the type parameters and we can make a Coproduct using the `cop`extension method. Just like `coproductOf`, if the type of the value isn't in the type parameters of the method call, it won't compile:
138
+
All we have to do is provide the type parameters and we can make a Coproduct using the extension methods. Just like the data classes, if the type of the value isn't in the type parameters of the method call, or it's not in the correct type parameter index, it won't compile:
Obviously, we're not just modeling errors for fun, we're going to handle them! All Coproducts have `fold` which allows us to condense the Coproduct down to a single type. For example, we could handle errors as such in a UI:
99
156
100
-
```kotlin:ank
157
+
```kotlin:ank:playground
101
158
import arrow.generic.*
102
-
import arrow.generic.coproduct3.Coproduct3
103
-
import arrow.generic.coproduct3.fold
159
+
import arrow.generic.coproduct3.*
104
160
105
161
fun handleCommonError(commonError: CommonServerError) {
162
+
println("Encountered a common error $commonError")
106
163
}
107
164
108
165
fun showCarAlreadyRegistered() {
166
+
println("Car is already registered")
109
167
}
110
168
111
169
fun callPolice() {
170
+
println("That car is stolen!!!!1!")
112
171
}
113
172
114
173
fun showCarSuccessfullyRegistered(car: Car) {
174
+
println("Successfully Registered!")
115
175
}
116
176
117
177
fun renderApiResult(apiResult: Coproduct3<CommonServerError, RegistrationError, Registration>) = apiResult.fold(
@@ -128,14 +188,17 @@ fun renderApiResult(apiResult: Coproduct3<CommonServerError, RegistrationError,
This example returns `Unit` because all of these are side effects, let's say our application was built for a command line and we just have to show a `String` for the result of the call (if only it was always that easy):
134
198
135
-
```kotlin:ank
199
+
```kotlin:ank:playground
136
200
import arrow.generic.*
137
-
import arrow.generic.coproduct3.Coproduct3
138
-
import arrow.generic.coproduct3.fold
201
+
import arrow.generic.coproduct3.*
139
202
140
203
fun renderApiResult(apiResult: Coproduct3<CommonServerError, RegistrationError, Registration>): String = apiResult.fold(
141
204
{ commonError ->
@@ -155,6 +218,10 @@ fun renderApiResult(apiResult: Coproduct3<CommonServerError, RegistrationError,
Here we're able to return the result of the `fold` and since it's exhaustively evaluated, we're forced to handle all cases! Neat! Let's say we also want to store the `Registration` object into our database when we successfully register a car. We don't really want to have to `fold` over every single case just to handle something for the `Registration`, this is where `select<T>` comes to the rescue!
@@ -163,10 +230,11 @@ Here we're able to return the result of the `fold` and since it's exhaustively e
163
230
164
231
We're able to take a Coproduct and `select` the type we care about from it. `select` returns an `Option`, if the value of the Coproduct was for the type you're trying to `select`, you'll get `Some`, if it was not the type used with `select`, you'll get `None`.
0 commit comments