|
| 1 | +import 'package:fpdart/fpdart.dart'; |
| 2 | + |
| 3 | +void helloWorld(String message) { |
| 4 | + print("Hello World: $message"); |
| 5 | +} |
| 6 | + |
| 7 | +/// 1️⃣ Pure function (Thunk) |
| 8 | +void Function() helloWorld1(String message) => () { |
| 9 | + print("Hello World: $message"); |
| 10 | + }; |
| 11 | + |
| 12 | +/// A thunk with no error is called [IO] in `fpdart` |
| 13 | +IO<void> helloWorld1Fpdart(String message) => IO(() { |
| 14 | + print("Hello World: $message"); |
| 15 | + }); |
| 16 | + |
| 17 | +/// 2️⃣ Explicit error |
| 18 | +/// Understand from the return type if and how the function may fail |
| 19 | +Either<Never, void> Function() helloWorld2(String message) => () { |
| 20 | + print("Hello World: $message"); |
| 21 | + return Either.of(null); |
| 22 | + }; |
| 23 | + |
| 24 | +/// A thunk with explicit error [Either] is called [IOEither] in `fpdart` |
| 25 | +IOEither<Never, void> helloWorld2Fpdart1(String message) => IOEither(() { |
| 26 | + print("Hello World: $message"); |
| 27 | + return Either.of(null); |
| 28 | + }); |
| 29 | + |
| 30 | +/// ...or using the `right` constructor |
| 31 | +IOEither<Never, void> helloWorld2Fpdart2(String message) => IOEither.right(() { |
| 32 | + print("Hello World: $message"); |
| 33 | + }); |
| 34 | + |
| 35 | +/// 3️⃣ Explicit dependency |
| 36 | +/// Provide the `print` method as a dependency instead of implicit global function |
| 37 | +
|
| 38 | +abstract class Console { |
| 39 | + void log(Object? object); |
| 40 | +} |
| 41 | + |
| 42 | +class ConsoleImpl implements Console { |
| 43 | + @override |
| 44 | + void log(Object? object) { |
| 45 | + print(object); |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +Either<Never, void> Function() Function(Console) helloWorld3(String message) => |
| 50 | + (console) => () { |
| 51 | + console.log("Hello World: $message"); |
| 52 | + return Either.of(null); |
| 53 | + }; |
| 54 | + |
| 55 | +/// Thunk (async) + error + dependency is called [ReaderTaskEither] in `fpdart` |
| 56 | +ReaderTaskEither<Console, Never, void> helloWorld3Fpdart(String message) => |
| 57 | + ReaderTaskEither((console) async { |
| 58 | + console.log("Hello World: $message"); |
| 59 | + return Either.of(null); |
| 60 | + }); |
| 61 | + |
| 62 | +void main(List<String> args) { |
| 63 | + final definition = helloWorld3("Sandro"); |
| 64 | + final thunk = definition(ConsoleImpl()); |
| 65 | + thunk(); |
| 66 | +} |
0 commit comments