Skip to content

Latest commit

 

History

History
55 lines (43 loc) · 1.39 KB

Either.md

File metadata and controls

55 lines (43 loc) · 1.39 KB
Error in user YAML: Alias parsing is not enabled.
---
uid: Recore.Either`2
example:
- *content
---

@Recore.Either2 creates a type with a value that can be one of two types. In this, it's similar to @Recore.Optional1, which you can think of like Either<T, null> with some extra functionality.

If you're familiar with TypeScript, you can think of @Recore.Either`2 as a union type:

TLeft | TRight

You create an instance of @Recore.Either`2 with one of its constructors, but the implicit conversion operator is pretty convenient too:

Either<string, int> either = "hello";

Like @Recore.Optional1, the main way to work with @Recore.Either2 is with Switch():

either.Switch(
    l => Console.WriteLine($"Value is a string: {l}"),
    r => Console.WriteLine($"Value is an int: {r}"));

you can also return a value:

var message = either.Switch(
    l => $"Value is a string: {l}",
    r => $"Value is an int: {r}");

Compared to @Recore.Optional1, though, where Switch() is more of a last resort when no higher-level idiom is available, @Recore.Either2 leans on Switch() heavily. You can think of @Recore.Either2 as being lower-level than @Recore.Optional1.

@Recore.Either2 also has OnLeft()andOnRight(), analogous to @Recore.Optional1's OnValue(). (Note that there's no OnEmpty(); you can just use if (!opt.HasValue) for that.)

Either<string, bool> newEither = either.OnRight(x => x > 0);