Skip to content

Instantly share code, notes, and snippets.

@dgt79
Last active March 14, 2019 23:07
Show Gist options
  • Select an option

  • Save dgt79/423f2b6bfe69e55eabbec2d10c6809c8 to your computer and use it in GitHub Desktop.

Select an option

Save dgt79/423f2b6bfe69e55eabbec2d10c6809c8 to your computer and use it in GitHub Desktop.
VAVR compose Try
package com.dgt;
import io.vavr.control.Option;
import io.vavr.control.Try;
import java.io.IOException;
import java.io.StringReader;
// based on http://blog.vavr.io/vavr-one-log-02/
public class ComposeVavrTry {
public static void main(String[] args) {
App app = new App();
Try.of(app::readHeader)
.map(Option::get)
.mapTry(app::readBody)
.onSuccess(s -> System.out.println(String.format("success: %s", s)))
.onFailure(throwable -> System.out.println(throwable.getMessage()));
}
public Option<String> readHeader() throws IOException {
try (FakeReader headerReader = new FakeReader("HeaderReader")) {
// if (true) throw new RuntimeException("BOOOYA");
// return Option.of(headerReader.fakeReading());
return Option.none();
}
}
public Option<String> readBody(String header) throws IOException {
try (FakeReader bodyReader = new FakeReader("BodyReader")) {
// if (true) throw new RuntimeException("BOOOYAKA");
return Option.of(String.format("%s - %s", header, bodyReader.fakeReading()));
}
}
class FakeReader extends StringReader implements AutoCloseable {
private final String s;
public FakeReader(String s) {
super(s);
this.s = s;
}
public String fakeReading() throws IOException {
StringBuffer buff = new StringBuffer();
int c = read();
while (c != -1) {
buff.append((char) c);
c = read();
}
return buff.toString();
}
@Override
public void close() {
super.close();
System.out.println(String.format("%s has been closed", s));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment