├── .github
├── ISSUE_TEMPLATE
│ ├── bug_report.md
│ └── feature_request.md
├── PULL_REQUEST_TEMPLATE.md
└── workflows
│ └── build.yml
├── .gitignore
├── CHANGELOG.md
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── analysis_options.yaml
├── example
└── example.dart
├── lib
├── result_type.dart
└── src
│ ├── failure.dart
│ ├── result.dart
│ └── success.dart
├── pubspec.lock
├── pubspec.yaml
└── test
├── failure_test.dart
├── result_test.dart
├── success_test.dart
├── test_all.dart
└── utils
└── mock_error.dart
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Describe the bug**
11 | A clear and concise description of what the bug is.
12 |
13 | **To Reproduce**
14 | Steps to reproduce the behavior:
15 | 1. Go to '...'
16 | 2. Click on '....'
17 | 3. Scroll down to '....'
18 | 4. See error
19 |
20 | **Expected behavior**
21 | A clear and concise description of what you expected to happen.
22 |
23 | **Screenshots**
24 | If applicable, add screenshots to help explain your problem.
25 |
26 | **Desktop (please complete the following information):**
27 | - OS: [e.g. iOS]
28 | - Browser [e.g. chrome, safari]
29 | - Version [e.g. 22]
30 |
31 | **Smartphone (please complete the following information):**
32 | - Device: [e.g. iPhone6]
33 | - OS: [e.g. iOS8.1]
34 | - Browser [e.g. stock browser, safari]
35 | - Version [e.g. 22]
36 |
37 | **Additional context**
38 | Add any other context about the problem here.
39 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Is your feature request related to a problem? Please describe.**
11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
12 |
13 | **Describe the solution you'd like**
14 | A clear and concise description of what you want to happen.
15 |
16 | **Describe alternatives you've considered**
17 | A clear and concise description of any alternative solutions or features you've considered.
18 |
19 | **Additional context**
20 | Add any other context or screenshots about the feature request here.
21 |
--------------------------------------------------------------------------------
/.github/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 | *Replace this paragraph with a description of what this PR is changing or adding, and why. Consider including before/after screenshots.*
2 |
3 | *List which issues are fixed by this PR. You must list at least one issue.*
4 |
5 | ## Pre-launch Checklist
6 |
7 | - [ ] I read and followed the [Effective Dart](https://dart.dev/guides/language/effective-dart/style).
8 | - [ ] I listed at least one issue or feature that this PR fixes or adds in the description above.
9 | - [ ] I updated/added relevant documentation (doc comments with `///`).
10 | - [ ] I updated/added relevant documentation to README.md.
11 | - [ ] I updated/added relevant code samples to [example](https://github.com/epam-cross-platform-lab/dart_result_type/blob/main/example/example.dart).
12 | - [ ] I added new tests to check the change I am making or feature I am adding, or Minikin said the PR is test-exempt.
13 | - [ ] All existing and new tests are passing.
14 |
15 | If you need help, consider asking for advice on [Twitter](https://twitter.com/minikin).
16 |
17 | Thank you for your contribution 🚀!
18 |
--------------------------------------------------------------------------------
/.github/workflows/build.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 |
3 | on:
4 | push:
5 | branches: [ main ]
6 | pull_request:
7 | branches:
8 | - "*"
9 |
10 | jobs:
11 | build:
12 | runs-on: ubuntu-latest
13 |
14 | container:
15 | image: google/dart:latest
16 |
17 | steps:
18 | - uses: actions/checkout@v2
19 |
20 | - name: Print Dart SDK version
21 | run: dart --version
22 |
23 | - name: Install dependencies
24 | run: dart pub get
25 |
26 | - name: Format
27 | run: dart format --set-exit-if-changed lib test example
28 |
29 | - name: Analyze project source
30 | run: dartanalyzer --fatal-infos --fatal-warnings lib test example
31 |
32 | - name: Run example
33 | run: dart run example/example.dart
34 |
35 | - name: Active coverage
36 | run: pub global activate coverage
37 |
38 | - name: Run tests
39 | run: dart test test/test_all.dart
40 |
41 | - name: Start Observatory
42 | run: dart
43 | --disable-service-auth-codes
44 | --enable-vm-service=8111
45 | --pause-isolates-on-exit
46 | --enable-asserts
47 | test/test_all.dart &
48 |
49 | - name: Collect coverage
50 | run: nohup pub global run coverage:collect_coverage
51 | --port=8111
52 | --out=coverage.json
53 | --wait-paused
54 | --resume-isolates
55 |
56 | - name: Format coverage
57 | run: pub global run coverage:format_coverage
58 | --lcov
59 | --in=coverage.json
60 | --out=lcov.info
61 | --packages=.packages
62 | --report-on=lib
63 |
64 | - name: Check Code Coverage
65 | uses: VeryGoodOpenSource/very_good_coverage@v1.1.1
66 | with:
67 | path: lcov.info
68 | min_coverage: 100
69 |
70 | - name: Upload coverage to Codecov
71 | uses: codecov/codecov-action@v1
72 | with:
73 | token: ${{ secrets.CODECOV_TOKEN }}
74 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Miscellaneous
2 | *.class
3 | *.log
4 | *.pyc
5 | *.swp
6 | .DS_Store
7 | .atom/
8 | .buildlog/
9 | .history
10 | .svn/
11 |
12 | # IntelliJ related
13 | *.iml
14 | *.ipr
15 | *.iws
16 | .idea/
17 |
18 | # The .vscode folder contains launch configuration and tasks you configure in
19 | # VS Code which you may wish to be included in version control, so this line
20 | # is commented out by default.
21 | #.vscode/
22 |
23 | # Flutter/Dart/Pub related
24 | **/doc/api/
25 | **/ios/Flutter/.last_build_id
26 | .dart_tool/
27 | .flutter-plugins
28 | .flutter-plugins-dependencies
29 | .packages
30 | .pub-cache/
31 | .pub/
32 | doc
33 | /build/
34 | .buildlog
35 | .dart_tool/
36 | web/experimental
37 |
38 | # Web related
39 | lib/generated_plugin_registrant.dart
40 |
41 | # Symbolication related
42 | app.*.symbols
43 |
44 | # Obfuscation related
45 | app.*.map.json
46 |
47 | # Android Studio will place build artifacts here
48 | /android/app/debug
49 | /android/app/profile
50 | /android/app/release
51 |
52 | # Or the files created by dart2js.
53 | *.dart.js
54 | *.js_
55 | *.js.deps
56 | *.js.map
57 |
58 | # Include when developing application packages.
59 | pubspec.lock
60 | coverage*
61 | nohup.out
62 | lcov.info
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | ## [0.1.0] - 04.04.2021.
2 |
3 | - Migrate to NNBD.
4 |
5 | ## 0.0.1 - 20.01.2021
6 |
7 | - Initial Release
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | In the interest of fostering an open and welcoming environment, we as
6 | contributors and maintainers pledge to making participation in our project and
7 | our community a harassment-free experience for everyone, regardless of age, body
8 | size, disability, ethnicity, sex characteristics, gender identity and expression,
9 | level of experience, education, socio-economic status, nationality, personal
10 | appearance, race, religion, or sexual identity and orientation.
11 |
12 | ## Our Standards
13 |
14 | Examples of behavior that contributes to creating a positive environment
15 | include:
16 |
17 | * Using welcoming and inclusive language
18 | * Being respectful of differing viewpoints and experiences
19 | * Gracefully accepting constructive criticism
20 | * Focusing on what is best for the community
21 | * Showing empathy towards other community members
22 |
23 | Examples of unacceptable behavior by participants include:
24 |
25 | * The use of sexualized language or imagery and unwelcome sexual attention or
26 | advances
27 | * Trolling, insulting/derogatory comments, and personal or political attacks
28 | * Public or private harassment
29 | * Publishing others' private information, such as a physical or electronic
30 | address, without explicit permission
31 | * Other conduct which could reasonably be considered inappropriate in a
32 | professional setting
33 |
34 | ## Our Responsibilities
35 |
36 | Project maintainers are responsible for clarifying the standards of acceptable
37 | behavior and are expected to take appropriate and fair corrective action in
38 | response to any instances of unacceptable behavior.
39 |
40 | Project maintainers have the right and responsibility to remove, edit, or
41 | reject comments, commits, code, wiki edits, issues, and other contributions
42 | that are not aligned to this Code of Conduct, or to ban temporarily or
43 | permanently any contributor for other behaviors that they deem inappropriate,
44 | threatening, offensive, or harmful.
45 |
46 | ## Scope
47 |
48 | This Code of Conduct applies both within project spaces and in public spaces
49 | when an individual is representing the project or its community. Examples of
50 | representing a project or community include using an official project e-mail
51 | address, posting via an official social media account, or acting as an appointed
52 | representative at an online or offline event. Representation of a project may be
53 | further defined and clarified by project maintainers.
54 |
55 | ## Enforcement
56 |
57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
58 | reported by contacting the project team at oleksandr_prokhorenko@epam.com. All
59 | complaints will be reviewed and investigated and will result in a response that
60 | is deemed necessary and appropriate to the circumstances. The project team is
61 | obligated to maintain confidentiality with regard to the reporter of an incident.
62 | Further details of specific enforcement policies may be posted separately.
63 |
64 | Project maintainers who do not follow or enforce the Code of Conduct in good
65 | faith may face temporary or permanent repercussions as determined by other
66 | members of the project's leadership.
67 |
68 | ## Attribution
69 |
70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
72 |
73 | [homepage]: https://www.contributor-covenant.org
74 |
75 | For answers to common questions about this code of conduct, see
76 | https://www.contributor-covenant.org/faq
77 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | When contributing to this repository, please first discuss the change you wish to make via issue,
4 | email, or any other method with the owners of this repository before making a change.
5 |
6 | Please note we have a code of conduct, please follow it in all your interactions with the project.
7 |
8 | ## Pull Request Process
9 |
10 | 1. Ensure any install or build dependencies are removed before the end of the layer when doing a
11 | build.
12 | 2. Update the README.md with details of changes to the interface, this includes new environment
13 | variables, exposed ports, useful file locations and container parameters.
14 | 3. Increase the version numbers in any examples files and the README.md to the new version that this
15 | Pull Request would represent. The versioning scheme we use is [SemVer](http://semver.org/).
16 | 4. You may merge the Pull Request in once you have the sign-off of two other developers, or if you
17 | do not have permission to do that, you may request the second reviewer to merge it for you.
18 |
19 | ## Code of Conduct
20 |
21 | ### Our Pledge
22 |
23 | In the interest of fostering an open and welcoming environment, we as
24 | contributors and maintainers pledge to making participation in our project and
25 | our community a harassment-free experience for everyone, regardless of age, body
26 | size, disability, ethnicity, gender identity and expression, level of experience,
27 | nationality, personal appearance, race, religion, or sexual identity and
28 | orientation.
29 |
30 | ### Our Standards
31 |
32 | Examples of behavior that contributes to creating a positive environment
33 | include:
34 |
35 | * Using welcoming and inclusive language
36 | * Being respectful of differing viewpoints and experiences
37 | * Gracefully accepting constructive criticism
38 | * Focusing on what is best for the community
39 | * Showing empathy towards other community members
40 |
41 | Examples of unacceptable behavior by participants include:
42 |
43 | * The use of sexualized language or imagery and unwelcome sexual attention or
44 | advances
45 | * Trolling, insulting/derogatory comments, and personal or political attacks
46 | * Public or private harassment
47 | * Publishing others' private information, such as a physical or electronic
48 | address, without explicit permission
49 | * Other conduct which could reasonably be considered inappropriate in a
50 | professional setting
51 |
52 | ### Our Responsibilities
53 |
54 | Project maintainers are responsible for clarifying the standards of acceptable
55 | behavior and are expected to take appropriate and fair corrective action in
56 | response to any instances of unacceptable behavior.
57 |
58 | Project maintainers have the right and responsibility to remove, edit, or
59 | reject comments, commits, code, wiki edits, issues, and other contributions
60 | that are not aligned to this Code of Conduct, or to ban temporarily or
61 | permanently any contributor for other behaviors that they deem inappropriate,
62 | threatening, offensive, or harmful.
63 |
64 | ### Scope
65 |
66 | This Code of Conduct applies both within project spaces and in public spaces
67 | when an individual is representing the project or its community. Examples of
68 | representing a project or community include using an official project e-mail
69 | address, posting via an official social media account, or acting as an appointed
70 | representative at an online or offline event. Representation of a project may be
71 | further defined and clarified by project maintainers.
72 |
73 | ### Enforcement
74 |
75 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
76 | reported by contacting the project team at djminikin at gmail dot com. All
77 | complaints will be reviewed and investigated and will result in a response that
78 | is deemed necessary and appropriate to the circumstances. The project team is
79 | obligated to maintain confidentiality with regard to the reporter of an incident.
80 | Further details of specific enforcement policies may be posted separately.
81 |
82 | Project maintainers who do not follow or enforce the Code of Conduct in good
83 | faith may face temporary or permanent repercussions as determined by other
84 | members of the project's leadership.
85 |
86 | ### Attribution
87 |
88 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
89 | available at [http://contributor-covenant.org/version/1/4][version]
90 |
91 | [homepage]: http://contributor-covenant.org
92 | [version]: http://contributor-covenant.org/version/1/4/
93 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
Result Type for Dart
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 | # Content
26 |
27 | - [Features](#features)
28 | - [Requirements](#requirements)
29 | - [Install](#install)
30 | - [Example](#example)
31 | - [Support](#support)
32 | - [License](#license)
33 |
34 | ## Features
35 |
36 | Result is a type that represents either [Success](https://github.com/epam-cross-platform-lab/dart_result_type/blob/main/lib/src/success.dart) or [Failure](https://github.com/epam-cross-platform-lab/dart_result_type/blob/main/lib/src/failure.dart).
37 |
38 | Inspired by [functional programming](http://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Either.html), [Rust](https://doc.rust-lang.org/std/result/enum.Result.html) and [Swift](https://developer.apple.com/documentation/swift/result).
39 |
40 | ## Requirements
41 |
42 | - Dart: 2.12.0+
43 |
44 | ## Install
45 |
46 | ```yaml
47 | dependencies:
48 | result_type: ^0.1.0
49 | ```
50 |
51 | ## Example
52 |
53 | The detailed example can be found at [result_type/example/example.dart](https://github.com/epam-cross-platform-lab/dart_result_type/blob/main/example/example.dart).
54 |
55 | ```dart
56 | import 'dart:async';
57 | import 'dart:convert';
58 | import 'dart:math';
59 |
60 | import 'package:http/http.dart' as http;
61 | import 'package:result_type/result_type.dart';
62 |
63 | void main() async {
64 | final random = Random();
65 | final client = http.Client();
66 | final result = await getPhotos(client);
67 |
68 | /// Do something with successful operation results or handle an error.
69 | if (result.isSuccess) {
70 | print('Photos Items: ${result.success}');
71 | } else {
72 | print('Error: ${result.failure}');
73 | }
74 |
75 | /// Apply transformation to successful operation results or handle an error.
76 | if (result.isSuccess) {
77 | final items = result.map((i) => i.where((j) => j.title.length > 60)).success;
78 | print('Number of Long Titles: ${items.length}');
79 | } else {
80 | print('Error: ${result.failure}');
81 | }
82 |
83 | /// In this example, note the difference in the result of using `map` and
84 | /// `flatMap` with a transformation that returns an result type.
85 | Result getNextInteger() => Success(random.nextInt(4));
86 | Result getNextAfterInteger(int n) => Success(random.nextInt(n + 1));
87 |
88 | final nextIntegerNestedResults = getNextInteger().map(getNextAfterInteger);
89 | print(nextIntegerNestedResults.runtimeType);
90 | /// `Prints`: Success, dynamic>
91 |
92 | final nextIntegerUnboxedResults = getNextInteger().flatMap(getNextAfterInteger);
93 | print(nextIntegerUnboxedResults.runtimeType);
94 | /// `Prints`: Success
95 |
96 | /// Use completion handler / callback style API if you want to.
97 | await getPhotos(client)
98 | ..result((photos) {
99 | print('Photos: $photos');
100 | }, (error) {
101 | print('Error: $error');
102 | });
103 | }
104 | ```
105 |
106 | To see examples of the following package in action:
107 |
108 | ```sh
109 | cd example && dart run
110 | ```
111 |
112 | ## Support
113 |
114 | Post issues and feature requests on the GitHub [issue tracker](https://github.com/epam-cross-platform-lab/dart_result_type/issues).
115 |
116 | ## License
117 |
118 | The source code of Result Type project is available under the Apache license.
119 | See the [LICENSE](https://github.com/epam-cross-platform-lab/dart_result_type/blob/main/LICENSE) file for more info.
120 |
--------------------------------------------------------------------------------
/analysis_options.yaml:
--------------------------------------------------------------------------------
1 | analyzer:
2 | language:
3 | strict-inference: true
4 | strict-raw-types: true
5 | errors:
6 | always_put_required_named_parameters_first: error
7 | avoid_relative_lib_imports: error
8 | missing_required_param: error
9 | no_duplicate_case_values: error
10 | prefer_const_constructors: error
11 |
12 | linter:
13 | rules:
14 | - avoid_shadowing_type_parameters
15 | - avoid_private_typedef_functions
16 | - avoid_returning_null
17 | - avoid_setters_without_getters
18 | - await_only_futures
19 | - camel_case_types
20 | - cancel_subscriptions
21 | - close_sinks
22 | - constant_identifier_names
23 | - control_flow_in_finally
24 | - directives_ordering
25 | - empty_constructor_bodies
26 | - empty_statements
27 | - hash_and_equals
28 | - implementation_imports
29 | - lines_longer_than_80_chars
30 | - non_constant_identifier_names
31 | - one_member_abstracts
32 | - package_names
33 | - package_prefixed_library_names
34 | - prefer_collection_literals
35 | - prefer_const_constructors
36 | - prefer_final_locals
37 | - prefer_function_declarations_over_variables
38 | - prefer_if_elements_to_conditional_expressions
39 | - prefer_interpolation_to_compose_strings
40 | - prefer_null_aware_operators
41 | - prefer_typing_uninitialized_variables
42 | - test_types_in_equals
43 | - type_annotate_public_apis
44 | - unnecessary_await_in_return
45 | - unnecessary_brace_in_string_interps
46 | - unnecessary_const
47 | - unnecessary_getters_setters
48 | - unnecessary_parenthesis
49 | - unnecessary_statements
50 | - use_to_and_as_if_applicable
51 | # Effective Dart Rules
52 | - avoid_catches_without_on_clauses
53 | - avoid_catching_errors
54 | - avoid_classes_with_only_static_members
55 | - avoid_equals_and_hash_code_on_mutable_classes
56 | - avoid_function_literals_in_foreach_calls
57 | - avoid_init_to_null
58 | - avoid_null_checks_in_equality_operators
59 | - avoid_positional_boolean_parameters
60 | - avoid_relative_lib_imports
61 | - avoid_return_types_on_setters
62 | - avoid_returning_this
63 | - avoid_types_on_closure_parameters
64 | - camel_case_extensions
65 | - curly_braces_in_flow_control_structures
66 | - file_names
67 | - library_names
68 | - library_prefixes
69 | - omit_local_variable_types
70 | - package_api_docs
71 | - prefer_adjacent_string_concatenation
72 | - prefer_equal_for_default_values
73 | - prefer_final_fields
74 | - prefer_generic_function_type_aliases
75 | - prefer_initializing_formals
76 | - prefer_is_empty
77 | - prefer_is_not_empty
78 | - prefer_iterable_whereType
79 | - prefer_mixin
80 | - prefer_relative_imports
81 | # - public_member_api_docs
82 | - slash_for_doc_comments
83 | - type_init_formals
84 | - unnecessary_lambdas
85 | - unnecessary_new
86 | - unnecessary_this
87 | - use_setters_to_change_properties
--------------------------------------------------------------------------------
/example/example.dart:
--------------------------------------------------------------------------------
1 | import 'dart:async';
2 | import 'dart:convert';
3 | import 'dart:math';
4 |
5 | import 'package:http/http.dart' as http;
6 | import 'package:result_type/result_type.dart';
7 |
8 | void main() async {
9 | final random = Random();
10 | final client = http.Client();
11 | final result = await getPhotos(client);
12 |
13 | /// Do something with successful operation results or handle an error.
14 | if (result.isSuccess) {
15 | print('Photos Items: ${result.success}');
16 | } else {
17 | print('Error: ${result.failure}');
18 | }
19 |
20 | /// Apply transformation to successful operation results or handle an error.
21 | if (result.isSuccess) {
22 | final items =
23 | result.map((i) => i.where((j) => j.title.length > 60)).success;
24 | print('Number of Long Titles: ${items.length}');
25 | } else {
26 | print('Error: ${result.failure}');
27 | }
28 |
29 | /// In this example, note the difference in the result of using `map` and
30 | /// `flatMap` with a transformation that returns an result type.
31 | Result getNextInteger() => Success(random.nextInt(4));
32 | Result getNextAfterInteger(int n) =>
33 | Success(random.nextInt(n + 1));
34 |
35 | final nextIntegerNestedResults = getNextInteger().map(getNextAfterInteger);
36 | print(nextIntegerNestedResults.runtimeType);
37 | // Prints: Success, dynamic>
38 |
39 | final nextIntegerUnboxedResults =
40 | getNextInteger().flatMap(getNextAfterInteger);
41 | print(nextIntegerUnboxedResults.runtimeType);
42 | // Prints: Success
43 |
44 | /// Use completion handler / callback style API if you want to.
45 | await getPhotos(client)
46 | ..result((photos) {
47 | print('Photos: $photos');
48 | }, (error) {
49 | print('Error: $error');
50 | });
51 | }
52 |
53 | class Photo {
54 | final int id;
55 | final String title;
56 | final String thumbnailUrl;
57 |
58 | const Photo({
59 | required this.id,
60 | required this.title,
61 | required this.thumbnailUrl,
62 | });
63 |
64 | factory Photo.fromJson(Map json) {
65 | print(json);
66 | return Photo(
67 | id: json['id'] as int,
68 | title: json['title'] as String,
69 | thumbnailUrl: json['thumbnailUrl'] as String,
70 | );
71 | }
72 |
73 | @override
74 | String toString() =>
75 | 'Photo(id: $id, title: $title, thumbnailUrl: $thumbnailUrl)';
76 | }
77 |
78 | extension PhotoExtension on Photo {
79 | static List parsePhotos(String responseBody) {
80 | final jsonObject = jsonDecode(responseBody) as Iterable;
81 | return jsonObject
82 | .map((json) => Photo.fromJson(Map.from(json)))
83 | .toList();
84 | }
85 | }
86 |
87 | class NetworkError implements Exception {
88 | final int code;
89 | final String description;
90 |
91 | const NetworkError({
92 | required this.code,
93 | required this.description,
94 | });
95 |
96 | @override
97 | String toString() => 'NetworkError(code: $code, description: $description)';
98 |
99 | static const notFound = NetworkError(code: 404, description: 'Not Found');
100 | }
101 |
102 | Future, NetworkError>> getPhotos(http.Client client) async {
103 | const path = 'https://jsonplaceholder.typicode.com/photos';
104 | try {
105 | final jsonString = await client.get(Uri.parse(path));
106 | return Success(PhotoExtension.parsePhotos(jsonString.body));
107 | } on NetworkError catch (_) {
108 | return Failure(NetworkError.notFound);
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/lib/result_type.dart:
--------------------------------------------------------------------------------
1 | export 'src/failure.dart';
2 | export 'src/result.dart';
3 | export 'src/success.dart';
4 |
--------------------------------------------------------------------------------
/lib/src/failure.dart:
--------------------------------------------------------------------------------
1 | import 'package:meta/meta.dart';
2 |
3 | import 'result.dart';
4 |
5 | /// A failure, storing a [Failure] value.
6 | @immutable
7 | class Failure extends Result {
8 | final F value;
9 |
10 | Failure(this.value);
11 |
12 | @override
13 | bool operator ==(Object o) {
14 | if (identical(this, o)) return true;
15 |
16 | return o is Failure && o.value == value;
17 | }
18 |
19 | @override
20 | int get hashCode => value.hashCode;
21 |
22 | @override
23 | String toString() => 'Failure: $value';
24 | }
25 |
--------------------------------------------------------------------------------
/lib/src/result.dart:
--------------------------------------------------------------------------------
1 | // ignore_for_file: lines_longer_than_80_chars, avoid_shadowing_type_parameters
2 | import 'failure.dart';
3 | import 'success.dart';
4 |
5 | /// Callbacks that return [Success] or [Failure].
6 | typedef Completion = void Function(T value);
7 |
8 | /// A value that represents either a success or a failure, including an
9 | /// associated value in each case.
10 | abstract class Result {
11 | /// Returns true if [Result] is [Failure].
12 | bool get isFailure => this is Failure;
13 |
14 | /// Returns true if [Result] is [Success].
15 | bool get isSuccess => this is Success;
16 |
17 | /// Returns a new value of [Failure] result.
18 | ///
19 | /// Handle an error or do something with successful operation results:
20 | ///
21 | /// ```dart
22 | /// final result = await getPhotos();
23 | ///
24 | /// if (result.isFailure) {
25 | /// print('Error: ${result.failure}');
26 | /// } else {
27 | /// print('Photos Items: ${result.success}');
28 | /// }
29 | /// ```
30 | ///
31 | F get failure {
32 | if (this is Failure) {
33 | return (this as Failure).value;
34 | }
35 |
36 | throw Exception(
37 | 'Make sure that result [isFailure] before accessing [failure]',
38 | );
39 | }
40 |
41 | /// Returns a new value of [Success] result.
42 | ///
43 | /// Do something with successful operation results or handle an error:
44 | ///
45 | /// ```dart
46 | /// final result = await getPhotos();
47 | ///
48 | /// if (result.isSuccess) {
49 | /// print('Photos Items: ${result.success}');
50 | /// } else {
51 | /// print('Error: ${result.failure}');
52 | /// }
53 | /// ```
54 | ///
55 | S get success {
56 | if (this is Success) {
57 | return (this as Success).value;
58 | }
59 |
60 | throw Exception(
61 | 'Make sure that result [isSuccess] before accessing [success]',
62 | );
63 | }
64 |
65 | /// Returns a new value of [Result] from closure
66 | /// either a success or a failure.
67 | ///
68 | /// This example shows how to use completion handler.
69 | ///
70 | /// ```dart
71 | /// final result = await getPhotos();
72 | ///
73 | /// await getPhotos(client)
74 | /// ..result((photos) {
75 | /// print('Photos: $photos');
76 | /// }, (error) {
77 | /// print('Error: $error');
78 | /// });
79 | /// ```
80 | ///
81 | void result(Completion success, Completion failure) {
82 | if (isSuccess) {
83 | final left = this as Success;
84 | success(left.value);
85 | }
86 |
87 | if (isFailure) {
88 | final right = this as Failure;
89 | failure(right.value);
90 | }
91 | }
92 |
93 | /// Maps a [Result] to [Result] by applying a function
94 | /// to a contained [Success] value, leaving an [Failure] value untouched.
95 | /// This function can be used to compose the results of two functions.
96 | ///
97 | /// Apply transformation to successful operation results or handle an error:
98 | ///
99 | /// ```dart
100 | /// final result = await getPhotos();
101 | ///
102 | /// if (result.isSuccess) {
103 | /// final items = result.map((i) => i.where((j) => j.title.length > 60)).success;
104 | /// print('Number of Long Titles: ${items.length}');
105 | /// } else {
106 | /// print('Error: ${result.failure}');
107 | /// }
108 | /// ```
109 | ///
110 | Result map(U Function(S) transform) {
111 | if (isSuccess) {
112 | final left = this as Success;
113 | return Success(transform(left.value));
114 | } else {
115 | final right = this as Failure;
116 | return Failure(right.value);
117 | }
118 | }
119 |
120 | /// Maps a [Result] to [Result] by applying a function
121 | /// to a contained [Failure] value, leaving an [Success] value untouched.
122 | ///
123 | /// This function can be used to pass through a successful result
124 | /// while applying transformation to [Failure].
125 | ///
126 | Result mapError(E Function(F) transform) {
127 | if (isSuccess) {
128 | final left = this as Success;
129 | return Success(left.value);
130 | } else {
131 | final right = this as Failure;
132 | return Failure(transform(right.value));
133 | }
134 | }
135 |
136 | /// Maps a [Result] to [Result] by applying a function
137 | /// to a contained [Success] value and unwrapping the produced result,
138 | /// leaving an [Failure] value untouched.
139 | ///
140 | /// Use this method to avoid a nested result when your transformation
141 | /// produces another [Result] type.
142 | ///
143 | /// In this example, note the difference in the result of using `map` and
144 | /// `flatMap` with a transformation that returns an result type.
145 | ///
146 | /// ```dart
147 | /// Result getNextInteger() => Success(random.nextInt(4));
148 | /// Result getNextAfterInteger(int n) => Success(random.nextInt(n + 1));
149 | ///
150 | /// final nextIntegerNestedResults = getNextInteger().map(getNextAfterInteger);
151 | /// print(nextIntegerNestedResults.runtimeType);
152 | /// `Prints: Success, dynamic>`
153 | ///
154 | /// final nextIntegerUnboxedResults = getNextInteger().flatMap(getNextAfterInteger);
155 | /// print(nextIntegerUnboxedResults.runtimeType);
156 | /// `Prints: Success`
157 | /// ```
158 | Result flatMap(Result Function(S) transform) {
159 | if (isSuccess) {
160 | final left = this as Success;
161 | return transform(left.value);
162 | } else {
163 | final right = this as Failure;
164 | return Failure(right.value);
165 | }
166 | }
167 |
168 | /// Maps a [Result] to [Result] by applying a function
169 | /// to a contained [Failure] value, leaving an [Success] value untouched.
170 | ///
171 | /// This function can be used to pass through a successful result
172 | /// while unboxing [Failure] and applying transformation to it.
173 | ///
174 | Result flatMapError(Result Function(F) transform) {
175 | if (isSuccess) {
176 | final left = this as Success;
177 | return Success(left.value);
178 | } else {
179 | final right = this as Failure;
180 | return transform(right.value);
181 | }
182 | }
183 | }
184 |
--------------------------------------------------------------------------------
/lib/src/success.dart:
--------------------------------------------------------------------------------
1 | import 'package:meta/meta.dart';
2 |
3 | import 'result.dart';
4 |
5 | /// A success, storing a [Success] value.
6 | @immutable
7 | class Success extends Result {
8 | final S value;
9 |
10 | Success(this.value);
11 |
12 | @override
13 | bool operator ==(Object o) {
14 | if (identical(this, o)) return true;
15 |
16 | return o is Success && o.value == value;
17 | }
18 |
19 | @override
20 | int get hashCode => value.hashCode;
21 |
22 | @override
23 | String toString() => 'Success: $value';
24 | }
25 |
--------------------------------------------------------------------------------
/pubspec.lock:
--------------------------------------------------------------------------------
1 | # Generated by pub
2 | # See https://dart.dev/tools/pub/glossary#lockfile
3 | packages:
4 | _fe_analyzer_shared:
5 | dependency: transitive
6 | description:
7 | name: _fe_analyzer_shared
8 | url: "https://pub.dartlang.org"
9 | source: hosted
10 | version: "19.0.0"
11 | analyzer:
12 | dependency: transitive
13 | description:
14 | name: analyzer
15 | url: "https://pub.dartlang.org"
16 | source: hosted
17 | version: "1.3.0"
18 | args:
19 | dependency: transitive
20 | description:
21 | name: args
22 | url: "https://pub.dartlang.org"
23 | source: hosted
24 | version: "2.0.0"
25 | async:
26 | dependency: transitive
27 | description:
28 | name: async
29 | url: "https://pub.dartlang.org"
30 | source: hosted
31 | version: "2.5.0"
32 | boolean_selector:
33 | dependency: transitive
34 | description:
35 | name: boolean_selector
36 | url: "https://pub.dartlang.org"
37 | source: hosted
38 | version: "2.1.0"
39 | charcode:
40 | dependency: transitive
41 | description:
42 | name: charcode
43 | url: "https://pub.dartlang.org"
44 | source: hosted
45 | version: "1.2.0"
46 | cli_util:
47 | dependency: transitive
48 | description:
49 | name: cli_util
50 | url: "https://pub.dartlang.org"
51 | source: hosted
52 | version: "0.3.0"
53 | collection:
54 | dependency: transitive
55 | description:
56 | name: collection
57 | url: "https://pub.dartlang.org"
58 | source: hosted
59 | version: "1.15.0"
60 | convert:
61 | dependency: transitive
62 | description:
63 | name: convert
64 | url: "https://pub.dartlang.org"
65 | source: hosted
66 | version: "3.0.0"
67 | coverage:
68 | dependency: transitive
69 | description:
70 | name: coverage
71 | url: "https://pub.dartlang.org"
72 | source: hosted
73 | version: "1.0.2"
74 | crypto:
75 | dependency: transitive
76 | description:
77 | name: crypto
78 | url: "https://pub.dartlang.org"
79 | source: hosted
80 | version: "3.0.1"
81 | file:
82 | dependency: transitive
83 | description:
84 | name: file
85 | url: "https://pub.dartlang.org"
86 | source: hosted
87 | version: "6.1.0"
88 | glob:
89 | dependency: transitive
90 | description:
91 | name: glob
92 | url: "https://pub.dartlang.org"
93 | source: hosted
94 | version: "2.0.1"
95 | http:
96 | dependency: "direct dev"
97 | description:
98 | name: http
99 | url: "https://pub.dartlang.org"
100 | source: hosted
101 | version: "0.13.1"
102 | http_multi_server:
103 | dependency: transitive
104 | description:
105 | name: http_multi_server
106 | url: "https://pub.dartlang.org"
107 | source: hosted
108 | version: "3.0.0"
109 | http_parser:
110 | dependency: transitive
111 | description:
112 | name: http_parser
113 | url: "https://pub.dartlang.org"
114 | source: hosted
115 | version: "4.0.0"
116 | io:
117 | dependency: transitive
118 | description:
119 | name: io
120 | url: "https://pub.dartlang.org"
121 | source: hosted
122 | version: "1.0.0"
123 | js:
124 | dependency: transitive
125 | description:
126 | name: js
127 | url: "https://pub.dartlang.org"
128 | source: hosted
129 | version: "0.6.3"
130 | logging:
131 | dependency: transitive
132 | description:
133 | name: logging
134 | url: "https://pub.dartlang.org"
135 | source: hosted
136 | version: "1.0.1"
137 | matcher:
138 | dependency: transitive
139 | description:
140 | name: matcher
141 | url: "https://pub.dartlang.org"
142 | source: hosted
143 | version: "0.12.10"
144 | meta:
145 | dependency: "direct main"
146 | description:
147 | name: meta
148 | url: "https://pub.dartlang.org"
149 | source: hosted
150 | version: "1.3.0"
151 | mime:
152 | dependency: transitive
153 | description:
154 | name: mime
155 | url: "https://pub.dartlang.org"
156 | source: hosted
157 | version: "1.0.0"
158 | node_preamble:
159 | dependency: transitive
160 | description:
161 | name: node_preamble
162 | url: "https://pub.dartlang.org"
163 | source: hosted
164 | version: "2.0.0"
165 | package_config:
166 | dependency: transitive
167 | description:
168 | name: package_config
169 | url: "https://pub.dartlang.org"
170 | source: hosted
171 | version: "2.0.0"
172 | path:
173 | dependency: transitive
174 | description:
175 | name: path
176 | url: "https://pub.dartlang.org"
177 | source: hosted
178 | version: "1.8.0"
179 | pedantic:
180 | dependency: transitive
181 | description:
182 | name: pedantic
183 | url: "https://pub.dartlang.org"
184 | source: hosted
185 | version: "1.11.0"
186 | pool:
187 | dependency: transitive
188 | description:
189 | name: pool
190 | url: "https://pub.dartlang.org"
191 | source: hosted
192 | version: "1.5.0"
193 | pub_semver:
194 | dependency: transitive
195 | description:
196 | name: pub_semver
197 | url: "https://pub.dartlang.org"
198 | source: hosted
199 | version: "2.0.0"
200 | shelf:
201 | dependency: transitive
202 | description:
203 | name: shelf
204 | url: "https://pub.dartlang.org"
205 | source: hosted
206 | version: "1.1.0"
207 | shelf_packages_handler:
208 | dependency: transitive
209 | description:
210 | name: shelf_packages_handler
211 | url: "https://pub.dartlang.org"
212 | source: hosted
213 | version: "3.0.0"
214 | shelf_static:
215 | dependency: transitive
216 | description:
217 | name: shelf_static
218 | url: "https://pub.dartlang.org"
219 | source: hosted
220 | version: "1.0.0"
221 | shelf_web_socket:
222 | dependency: transitive
223 | description:
224 | name: shelf_web_socket
225 | url: "https://pub.dartlang.org"
226 | source: hosted
227 | version: "1.0.1"
228 | source_map_stack_trace:
229 | dependency: transitive
230 | description:
231 | name: source_map_stack_trace
232 | url: "https://pub.dartlang.org"
233 | source: hosted
234 | version: "2.1.0"
235 | source_maps:
236 | dependency: transitive
237 | description:
238 | name: source_maps
239 | url: "https://pub.dartlang.org"
240 | source: hosted
241 | version: "0.10.10"
242 | source_span:
243 | dependency: transitive
244 | description:
245 | name: source_span
246 | url: "https://pub.dartlang.org"
247 | source: hosted
248 | version: "1.8.1"
249 | stack_trace:
250 | dependency: transitive
251 | description:
252 | name: stack_trace
253 | url: "https://pub.dartlang.org"
254 | source: hosted
255 | version: "1.10.0"
256 | stream_channel:
257 | dependency: transitive
258 | description:
259 | name: stream_channel
260 | url: "https://pub.dartlang.org"
261 | source: hosted
262 | version: "2.1.0"
263 | string_scanner:
264 | dependency: transitive
265 | description:
266 | name: string_scanner
267 | url: "https://pub.dartlang.org"
268 | source: hosted
269 | version: "1.1.0"
270 | term_glyph:
271 | dependency: transitive
272 | description:
273 | name: term_glyph
274 | url: "https://pub.dartlang.org"
275 | source: hosted
276 | version: "1.2.0"
277 | test:
278 | dependency: "direct dev"
279 | description:
280 | name: test
281 | url: "https://pub.dartlang.org"
282 | source: hosted
283 | version: "1.16.8"
284 | test_api:
285 | dependency: transitive
286 | description:
287 | name: test_api
288 | url: "https://pub.dartlang.org"
289 | source: hosted
290 | version: "0.3.0"
291 | test_core:
292 | dependency: transitive
293 | description:
294 | name: test_core
295 | url: "https://pub.dartlang.org"
296 | source: hosted
297 | version: "0.3.19"
298 | typed_data:
299 | dependency: transitive
300 | description:
301 | name: typed_data
302 | url: "https://pub.dartlang.org"
303 | source: hosted
304 | version: "1.3.0"
305 | vm_service:
306 | dependency: transitive
307 | description:
308 | name: vm_service
309 | url: "https://pub.dartlang.org"
310 | source: hosted
311 | version: "6.2.0"
312 | watcher:
313 | dependency: transitive
314 | description:
315 | name: watcher
316 | url: "https://pub.dartlang.org"
317 | source: hosted
318 | version: "1.0.0"
319 | web_socket_channel:
320 | dependency: transitive
321 | description:
322 | name: web_socket_channel
323 | url: "https://pub.dartlang.org"
324 | source: hosted
325 | version: "2.0.0"
326 | webkit_inspection_protocol:
327 | dependency: transitive
328 | description:
329 | name: webkit_inspection_protocol
330 | url: "https://pub.dartlang.org"
331 | source: hosted
332 | version: "1.0.0"
333 | yaml:
334 | dependency: transitive
335 | description:
336 | name: yaml
337 | url: "https://pub.dartlang.org"
338 | source: hosted
339 | version: "3.1.0"
340 | sdks:
341 | dart: ">=2.12.0 <3.0.0"
342 |
--------------------------------------------------------------------------------
/pubspec.yaml:
--------------------------------------------------------------------------------
1 | name: result_type
2 | version: 0.1.0
3 | description: Result Type represents either a success or a failure, including an associated value in each case.
4 | repository: https://github.com/epam-cross-platform-lab/dart_result_type
5 |
6 | environment:
7 | sdk: ">=2.12.0 <3.0.0"
8 |
9 | dependencies:
10 | meta: ^1.3.0
11 |
12 | dev_dependencies:
13 | http: ^0.13.1
14 | test: ^1.16.8
--------------------------------------------------------------------------------
/test/failure_test.dart:
--------------------------------------------------------------------------------
1 | import 'package:result_type/src/failure.dart';
2 | import 'package:test/test.dart';
3 |
4 | import 'utils/mock_error.dart';
5 |
6 | void main() {
7 | group('Failure', () {
8 | test('Should return _TestError', () {
9 | final failure = Failure(const MockError(1));
10 | expect(failure.value.code, 1);
11 | });
12 |
13 | test('Two identical Failures should be equal', () {
14 | final failure1 = Failure(const MockError(1));
15 | final failure2 = Failure(const MockError(1));
16 |
17 | expect(failure1, failure2);
18 | });
19 |
20 | test('Two identical Failures should have the same hashCode', () {
21 | final failure1 = Failure(const MockError(1));
22 | final failure2 = Failure(const MockError(1));
23 |
24 | expect(failure1.hashCode, failure2.hashCode);
25 | });
26 |
27 | test('Can print to string', () {
28 | final failure = Failure(const MockError(1));
29 | expect(failure.toString(), 'Failure: MockError(code: 1)');
30 | });
31 | });
32 | }
33 |
--------------------------------------------------------------------------------
/test/result_test.dart:
--------------------------------------------------------------------------------
1 | import 'dart:math';
2 |
3 | import 'package:result_type/result_type.dart';
4 | import 'package:test/test.dart';
5 |
6 | import 'utils/mock_error.dart';
7 |
8 | void main() {
9 | group('Result:', () {
10 | Random? random;
11 |
12 | setUp(() {
13 | random = Random();
14 | });
15 |
16 | tearDown(() {
17 | random = null;
18 | });
19 |
20 | test('Returns Success', () {
21 | final result = getUser(value: true);
22 | if (result.isSuccess) {
23 | print('Success: ${result.success}');
24 | } else {
25 | print('Error: ${result.failure}');
26 | }
27 |
28 | expect(result.success, 'John Doe');
29 | });
30 |
31 | test('Returns Failure', () {
32 | final result = getUser(value: false);
33 | if (result.isSuccess) {
34 | print('Success: ${result.success}');
35 | } else {
36 | print('Error: ${result.failure}');
37 | }
38 |
39 | expect(result.failure, const MockError(404));
40 | });
41 |
42 | test('Returns Success From Callbacks', () {
43 | getUser(value: true)
44 | ..result((success) {
45 | expect(success, 'John Doe');
46 | }, (_) {});
47 | });
48 |
49 | test('Returns Failure From Callbacks', () {
50 | getUser(value: false)
51 | ..result((_) {}, (error) {
52 | expect(error, const MockError(404));
53 | });
54 | });
55 |
56 | test(
57 | '''Throw Exception when accessing success value without checking if isSuccess''',
58 | () {
59 | final result = getUser(value: false);
60 |
61 | expect(() => result.success, throwsException);
62 | });
63 |
64 | test(
65 | '''Throw Exception when accessing failure value without checking if isFailure''',
66 | () {
67 | final result = getUser(value: true);
68 |
69 | expect(() => result.failure, throwsException);
70 | });
71 |
72 | test('Apply map transformation to successful operation results', () {
73 | final result = getUser(value: true);
74 | final user = result.map((i) => i.toUpperCase()).success;
75 |
76 | expect(user, 'JOHN DOE');
77 | });
78 |
79 | test(
80 | '''Throw an error from map transformation without applying transformation to error type''',
81 | () {
82 | final result = getUser(value: false);
83 | final error = result.map((i) => i.toUpperCase()).failure;
84 |
85 | expect(error, const MockError(404));
86 | });
87 |
88 | test('Apply mapError transformation to failure type', () {
89 | final error =
90 | getUser(value: false).mapError((i) => MockError(i.code - 4)).failure;
91 |
92 | expect(error.code, const MockError(400).code);
93 | });
94 |
95 | test(
96 | '''Returns successful result without applying mapError transformation''',
97 | () {
98 | final maybeError =
99 | getUser(value: true).mapError((i) => MockError(i.code - 4));
100 |
101 | if (maybeError.isFailure) {
102 | } else {
103 | expect(maybeError.success, 'John Doe');
104 | }
105 | });
106 |
107 | test('Apply flatMap transformation to successful operation results', () {
108 | Result getNextInteger() => Success(random!.nextInt(4));
109 | Result getNextAfterInteger(int n) =>
110 | Success(random!.nextInt(n + 1));
111 |
112 | final nextIntegerUnboxedResults =
113 | getNextInteger().flatMap(getNextAfterInteger);
114 |
115 | expect(
116 | nextIntegerUnboxedResults,
117 | const TypeMatcher>(),
118 | );
119 | });
120 |
121 | test('flatMap does not apply transformation to Failure', () {
122 | Result getNextInteger() => Failure(const MockError(451));
123 | Result getNextAfterInteger(int n) =>
124 | Failure(const MockError(404));
125 |
126 | final nextIntegerUnboxedResults =
127 | getNextInteger().flatMap(getNextAfterInteger);
128 |
129 | expect(
130 | nextIntegerUnboxedResults,
131 | const TypeMatcher>(),
132 | );
133 | });
134 |
135 | test('Apply flatMapError transformation to failure operation results', () {
136 | Result getNextInteger() => Failure(const MockError(451));
137 | Result getNextAfterInteger(MockError error) =>
138 | Failure(MockError(error.code));
139 |
140 | final nextIntegerUnboxedResults =
141 | getNextInteger().flatMapError(getNextAfterInteger);
142 |
143 | expect(
144 | nextIntegerUnboxedResults,
145 | const TypeMatcher>(),
146 | );
147 | });
148 |
149 | test(
150 | '''flatMapError does not apply transformation to success operation results''',
151 | () {
152 | Result getNextInteger() => Success(random!.nextInt(4));
153 | Result getNextAfterInteger(MockError error) =>
154 | Failure(MockError(error.code));
155 |
156 | final nextIntegerUnboxedResults =
157 | getNextInteger().flatMapError(getNextAfterInteger);
158 |
159 | expect(
160 | nextIntegerUnboxedResults,
161 | const TypeMatcher>(),
162 | );
163 | });
164 | });
165 | }
166 |
167 | Result getUser({required bool value}) =>
168 | value ? Success('John Doe') : Failure(const MockError(404));
169 |
--------------------------------------------------------------------------------
/test/success_test.dart:
--------------------------------------------------------------------------------
1 | import 'package:result_type/src/success.dart';
2 | import 'package:test/test.dart';
3 |
4 | import 'utils/mock_error.dart';
5 |
6 | void main() {
7 | group('Success', () {
8 | test('Should have a value 0', () {
9 | final success = Success(0);
10 | expect(success.value, 0);
11 | });
12 |
13 | test('Two identical Successes should be equal', () {
14 | final success1 = Success(0);
15 | final success2 = Success(0);
16 |
17 | expect(success1, success2);
18 | });
19 |
20 | test('Two identical Successes should have the same hashCode', () {
21 | final success1 = Success(0);
22 | final success2 = Success(0);
23 |
24 | expect(success1.hashCode, success2.hashCode);
25 | });
26 |
27 | test('Can print to string', () {
28 | final success = Success(0);
29 | expect(success.toString(), 'Success: 0');
30 | });
31 | });
32 | }
33 |
--------------------------------------------------------------------------------
/test/test_all.dart:
--------------------------------------------------------------------------------
1 | import 'package:test/test.dart';
2 |
3 | import 'failure_test.dart' as failure;
4 | import 'result_test.dart' as result;
5 | import 'success_test.dart' as success;
6 |
7 | void main() {
8 | group('success', success.main);
9 | group('failure', failure.main);
10 | group('result', result.main);
11 | }
12 |
--------------------------------------------------------------------------------
/test/utils/mock_error.dart:
--------------------------------------------------------------------------------
1 | class MockError implements Exception {
2 | final int code;
3 |
4 | const MockError(this.code);
5 |
6 | @override
7 | String toString() => 'MockError(code: $code)';
8 | }
9 |
--------------------------------------------------------------------------------