Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes patmat corner case that might produce a ClassCastException #2405

Merged
merged 2 commits into from
Apr 8, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions vavr/generator/Generator.scala
Original file line number Diff line number Diff line change
Expand Up @@ -1041,7 +1041,11 @@ def generateMainClasses(): Unit = {

@Override
public boolean isDefinedAt(T obj) {
return predicate.test(obj);
try {
return predicate.test(obj);
} catch (ClassCastException x) {
return false;
}
}
};
}
Expand Down Expand Up @@ -2983,7 +2987,7 @@ def generateTestClasses(): Unit = {
public void shouldPassIssue2401() {
final $SeqType<String> empty = $StreamType.empty();
try {
final String matched = Match(empty).of(
Match(empty).of(
Case($$($ListType.empty()), ignored -> "list")
);
fail("expected MatchError");
Expand All @@ -2992,6 +2996,19 @@ def generateTestClasses(): Unit = {
}
}

@$test
public void shouldCatchClassCastExceptionWhenPredicateHasDifferentType() {
try {
final Object o = "";
Match(o).of(
Case($$((Integer i) -> true), "never")
);
fail("expected MatchError");
} catch (MatchError err) {
// ok!
}
}

// -- Match patterns

static class ClzMatch {}
Expand Down
6 changes: 5 additions & 1 deletion vavr/src-gen/main/java/io/vavr/API.java
Original file line number Diff line number Diff line change
Expand Up @@ -5069,7 +5069,11 @@ public T apply(T obj) {

@Override
public boolean isDefinedAt(T obj) {
return predicate.test(obj);
try {
return predicate.test(obj);
} catch (ClassCastException x) {
return false;
}
}
};
}
Expand Down
15 changes: 14 additions & 1 deletion vavr/src-gen/test/java/io/vavr/APITest.java
Original file line number Diff line number Diff line change
Expand Up @@ -1412,7 +1412,7 @@ public void shouldReturnNoneWhenApplyingCaseGivenPredicateAndValue() {
public void shouldPassIssue2401() {
final Seq<String> empty = Stream.empty();
try {
final String matched = Match(empty).of(
Match(empty).of(
Case($(List.empty()), ignored -> "list")
);
fail("expected MatchError");
Expand All @@ -1421,6 +1421,19 @@ public void shouldPassIssue2401() {
}
}

@Test
public void shouldCatchClassCastExceptionWhenPredicateHasDifferentType() {
try {
final Object o = "";
Match(o).of(
Case($((Integer i) -> true), "never")
);
fail("expected MatchError");
} catch (MatchError err) {
// ok!
}
}

// -- Match patterns

static class ClzMatch {}
Expand Down