Last active
February 27, 2020 18:27
-
-
Save harikrishnan83/3c4359bbb91e57eba7b962dc9300c6cc to your computer and use it in GitHub Desktop.
Kotlin Railway Oriented Programming
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
//Kotlin Railway Oriented Programming | |
sealed class Result<T> | |
data class Success<T>(val message: T) : Result<T>() | |
data class Failure<T>(val errorMessage: String) : Result<T>() | |
infix fun <T, U> Result<T>.then(f: (T) -> Result<U>) = | |
when (this) { | |
is Success -> f(this.message) | |
is Failure -> Failure(this.errorMessage) | |
} | |
infix fun <T, U> T.pipeTo(f: (T) -> Result<U>) = Success(this) then f | |
infix fun <T> Result<T>.error(f: (String) -> Result<T>) = | |
if (this is Failure) f(this.errorMessage) else this | |
class HttpRequest(private val url: String, private val method: HttpMethod, private val body: String) { | |
fun matches(anotherRequest: HttpRequest) = | |
anotherRequest pipeTo | |
::matchUrl then | |
::matchMethod then | |
::matchBody error | |
::handleError | |
private fun matchUrl(anotherRequest: HttpRequest): Result<HttpRequest> { | |
if (this.url != anotherRequest.url) | |
return Failure("URL did not match. ${this.url} not equal to ${anotherRequest.url}") | |
return Success(anotherRequest) | |
} | |
private fun matchMethod(anotherRequest: HttpRequest): Result<HttpRequest> { | |
if (this.method != anotherRequest.method) | |
return Failure("Method did not match. ${this.method} not equal to ${anotherRequest.method}") | |
return Success(anotherRequest) | |
} | |
private fun matchBody(anotherRequest: HttpRequest): Result<HttpRequest> { | |
if (this.body != anotherRequest.body) | |
return Failure("Body did not match. ${this.body} not equal to ${anotherRequest.body}") | |
return Success(anotherRequest) | |
} | |
private fun handleError(errorMessage: String): Result<HttpRequest> { | |
return Failure(errorMessage) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment