Skip to content

Commit

Permalink
Fixes patmat corner case that might produce a ClassCastException (vav…
Browse files Browse the repository at this point in the history
…r-io#2405)

* Fixes patmat corner case that might produce a ClassCastException

* src-gen changes
  • Loading branch information
danieldietrich authored and Theodor A. Dumitrescu committed Dec 11, 2019
1 parent 212787e commit 04c0b61
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 4 deletions.
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

0 comments on commit 04c0b61

Please sign in to comment.