Created
June 18, 2017 01:20
-
-
Save mguilherme/73f41cd15ca3d3ca95d2e0138cda4696 to your computer and use it in GitHub Desktop.
VAVR Match Case
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
| package com.guilherme.miguel.vavr; | |
| import com.guilherme.miguel.vavr.exception.AnotherException; | |
| import com.guilherme.miguel.vavr.exception.OtherException; | |
| import com.guilherme.miguel.vavr.exception.SomeException; | |
| import io.vavr.control.Try; | |
| import lombok.extern.slf4j.Slf4j; | |
| import java.util.stream.IntStream; | |
| import static io.vavr.API.*; | |
| import static io.vavr.Predicates.instanceOf; | |
| import static java.lang.String.format; | |
| /** | |
| * @author Miguel Guilherme | |
| */ | |
| @Slf4j | |
| public class MatchCase { | |
| public static void main(String... args) { | |
| IntStream.rangeClosed(0, 10) | |
| .mapToObj(MatchCase::doWork) | |
| .forEach(n -> log.info(n)); | |
| } | |
| /** | |
| * Execute Operation with Match Case | |
| */ | |
| private static String doWork(Integer number) { | |
| return Try.of(() -> getNumber(number)) | |
| .recover(x -> Match(x).of( | |
| Case($(instanceOf(SomeException.class)), t -> format("Error: %s", t)), | |
| Case($(instanceOf(OtherException.class)), t -> format("Error: %s", t)), | |
| Case($(instanceOf(AnotherException.class)), t -> format("Error: %s", t)) | |
| )) | |
| .getOrElse("Something else happened"); | |
| } | |
| /** | |
| * Dummy method | |
| * | |
| * @param number the number | |
| * @return the number itself | |
| */ | |
| private static String getNumber(Integer number) throws SomeException, OtherException, AnotherException { | |
| switch (number) { | |
| case 4: | |
| throw new SomeException(); | |
| case 2: | |
| throw new OtherException(); | |
| case 6: | |
| throw new AnotherException(); | |
| case 9: | |
| throw new RuntimeException(); | |
| default: | |
| return String.valueOf(number); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment