Last active
September 24, 2020 11:28
-
-
Save airvin/eabc99a9552a0573afd2dd9a13e75948 to your computer and use it in GitHub Desktop.
Example of how to use fold on an Either Error type to reduce the left and right cases to a single type. The `requestStateVerbose` includes all the type declarations to make it clearer. The `requestStateConcise` has shortened it to a single expression.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
suspend fun requestStateVerbose(request: Request): ProofResponse { | |
val eitherErrorProof: Either<Error, Proof> = createProof(request.key) | |
val proofResponse: ProofResponse = eitherErrorProof.fold({ error: Error -> | |
println("Returning error: ${error.message}\n") | |
ProofResponse.newBuilder() | |
.setError(error.message) | |
.build() | |
}, { proof: Proof -> | |
println("Returning proof: $proof\n") | |
ProofResponse.newBuilder() | |
.setProof(proof) | |
.build() | |
}) | |
return proofResponse | |
} | |
suspend fun requestStateConcise(request: Request): ProofResponse = | |
createProof(request.key).fold({ error -> | |
println("Returning error: ${error.message}\n") | |
ProofResponse.newBuilder() | |
.setError(error.message) | |
.build() | |
},{ proof -> | |
println("Returning proof: $proof\n") | |
ProofResponse.newBuilder() | |
.setProof(proof) | |
.build() | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment