Created
February 11, 2020 16:42
-
-
Save vaslabs/4d6240a893b0f97e24cd4523cb3f344a to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import io.vavr.control.Either; | |
import io.vavr.control.Try; | |
import java.time.Clock; | |
import java.time.ZonedDateTime; | |
import java.util.List; | |
import java.util.Optional; | |
import java.util.function.Function; | |
class Snippets { | |
public static Either<String, Integer> toInt(String text) { | |
return Try.of(() -> Integer.parseInt(text)) //Try<Integer> | |
.toEither() //Either<Throwable, Integer> | |
.mapLeft(t -> "Expected an integer for days but found: " + text); //Either<Throwable, String> | |
} | |
public static Either<String, ZonedDateTime> addDaysToNow(int days, ZonedDateTime now) { | |
return Try.of(() -> now.plusDays(days)) | |
.toEither() | |
.mapLeft(t -> "Given " + days + " exceed the date range"); | |
} | |
static class UserRequest { | |
final String days; | |
final ZonedDateTime now; | |
UserRequest(String days, ZonedDateTime now) { | |
this.days = days; | |
this.now = now; | |
} | |
} | |
static class ValidatedUserInput { | |
final int days; | |
final ZonedDateTime now; | |
ValidatedUserInput(int days, ZonedDateTime now) { | |
this.days = days; | |
this.now = now; | |
} | |
} | |
public static Either<String, ZonedDateTime> serveUser(UserRequest userRequest) { | |
return toInt(userRequest.days) //Either<String, Integer> | |
.map( | |
days -> new ValidatedUserInput(days, userRequest.now) | |
) //Either<String, ValidatedUserInput> | |
.flatMap( | |
validatedInput -> addDaysToNow(validatedInput.days, validatedInput.now) | |
); //Either<String, ZonedDateTime> | |
} | |
public static Function<String, Function<Clock, Either<String, ZonedDateTime>>> serveUserFunction() { | |
return days -> //String => | |
clock -> // Clock => | |
serveUser( | |
new UserRequest(days, ZonedDateTime.now(clock)) | |
); //Either<String, ZonedDateTime> | |
} | |
public static void main(String[] args) { | |
Clock clock = Clock.systemUTC(); | |
String days = args[0]; | |
serveUserFunction().apply(days).apply(clock); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
handle null values in pojos
Example