Skip to content

Instantly share code, notes, and snippets.

@airvin
Last active September 24, 2020 11:28
Show Gist options
  • Save airvin/eabc99a9552a0573afd2dd9a13e75948 to your computer and use it in GitHub Desktop.
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.
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