11package com .sourcegraph .semanticdb_javac ;
22
33import java .util .NoSuchElementException ;
4- import java .util .Objects ;
5- import java .util .function .Function ;
64
75/**
86 * A Java implementation of Rust's <code>Result[T, E]</code> type, or Scala's <code>Either[A, B]
@@ -17,7 +15,7 @@ private enum Kind {
1715 Error ;
1816 }
1917
20- private Kind kind ;
18+ private final Kind kind ;
2119 private final T ok ;
2220 private final E error ;
2321
@@ -31,69 +29,23 @@ private Result(Kind kind, T ok, E error) {
3129 this .ok = ok ;
3230 }
3331
34- @ Override
35- public boolean equals (Object o ) {
36- if (this == o ) return true ;
37- if (o == null || getClass () != o .getClass ()) return false ;
38- Result <?, ?> result = (Result <?, ?>) o ;
39- return kind == result .kind
40- && Objects .equals (error , result .error )
41- && Objects .equals (ok , result .ok );
42- }
43-
44- @ Override
45- public int hashCode () {
46- return Objects .hash (kind , error , ok );
47- }
48-
49- @ Override
50- public String toString () {
51- switch (kind ) {
52- case Ok :
53- return "Error(" + error + ")" ;
54- case Error :
55- return "Ok(" + ok + ")" ;
56- default :
57- return "Result{" + "kind=" + kind + ", error=" + error + ", ok=" + ok + '}' ;
58- }
59- }
60-
61- public <C > C fold (Function <T , C > onOk , Function <E , C > onError ) {
62- switch (kind ) {
63- case Ok :
64- return onOk .apply (ok );
65- case Error :
66- return onError .apply (error );
67- default :
68- throw new IllegalArgumentException (this .toString ());
69- }
70- }
71-
72- public <C > Result <C , E > map (Function <T , C > fn ) {
73- return this .fold (left -> Result .ok (fn .apply (left )), Result ::error );
74- }
75-
7632 public boolean isOk () {
7733 return kind == Kind .Ok ;
7834 }
7935
80- public boolean isError () {
81- return kind == Kind .Error ;
82- }
83-
8436 public T getOrThrow () {
8537 if (kind == Kind .Ok ) {
8638 return ok ;
8739 } else {
88- throw new NoSuchElementException ("no left value on " + this . toString () );
40+ throw new NoSuchElementException ("no ok value on Result.Error( " + error + ")" );
8941 }
9042 }
9143
9244 public E getErrorOrThrow () {
9345 if (kind == Kind .Error ) {
9446 return error ;
9547 } else {
96- throw new NoSuchElementException ("no left value on " + this . toString () );
48+ throw new NoSuchElementException ("no error value on Result.Ok( " + ok + ")" );
9749 }
9850 }
9951
0 commit comments