Skip to content

Instantly share code, notes, and snippets.

@antonyharfield
Last active April 16, 2019 07:43
Show Gist options
  • Save antonyharfield/ccf22fabdb56714602d11be8efb7633c to your computer and use it in GitHub Desktop.
Save antonyharfield/ccf22fabdb56714602d11be8efb7633c to your computer and use it in GitHub Desktop.
sealed class Result<T>
data class Success<T>(val value: T): Result<T>()
data class Failure<T>(val errorMessage: String): Result<T>()
infix fun <T,U> Result<T>.compose(f: (T) -> Result<U>) =
when (this) {
is Success -> f(this.value)
is Failure -> Failure(this.errorMessage)
}
fun main(args: Array<String>) {
(input("Enter your name") compose ::notBlank compose ::lengthWithin10).let {
when (it) {
is Success -> println("Your name is: ${it.value}")
is Failure -> println("Something went wrong: ${it.errorMessage}")
}
}
}
fun input(prompt: String): Result<String> {
print("$prompt: ")
val line = readLine()
if (line == null) {
return Failure("Unexpected end of input")
}
return Success(line)
}
fun notBlank(input: String): Result<String> =
if (input != "") Success(input) else Failure("Blank input")
fun lengthWithin10(input: String): Result<String> =
if (input.length <= 10) Success(input) else Failure("Input should be within 10 letters")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment