Skip to content

Commit

Permalink
Update JSONTest
Browse files Browse the repository at this point in the history
  • Loading branch information
biboudis committed Mar 22, 2024
1 parent 2f6642b commit 1ecb187
Showing 1 changed file with 30 additions and 18 deletions.
48 changes: 30 additions & 18 deletions test/langtools/tools/javac/patterns/declarations/JSONTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,36 @@
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;

public class JSONTest {

public static void main(String[] args) {
JSONObject j = new JSONObject(
Map.of("configuration", new JSONString("7"), "services", new JSONArray(List.of(
new JSONObject(Map.of("name", new JSONString("a"), "id", new JSONNumber(3))),
new JSONObject(Map.of("name", new JSONString("b"), "id", new JSONNumber(4)))))));

assertEquals("a", serviceToNameView().apply(j));
}

record View<A, B>(Function<A, B> f) implements Function<A, B> {
@Override
public B apply(A a) {
return f.apply(a);
}
public static <A, B> View<A, B> of(Function<A, B> f) {
return new View<>(f);
}
}

private static View<JSONObject, String> serviceToNameView() {
return View.of((JSONObject j) -> switch (Service.Of(j)) {
case Service(String name, int id) -> name;
default -> throw new IllegalStateException("Unexpected value: " + j);
});
}

sealed interface JSONValue {
}

Expand Down Expand Up @@ -78,24 +105,9 @@ public pattern Service(String name, int id) {
}
}

public static void main(String[] args) {
JSONObject j = new JSONObject(
Map.of(
"configuration", new JSONString("7"),
"services", new JSONArray(List.of(
new JSONObject(
Map.of("name", new JSONString("a"),
"id", new JSONNumber(3))),
new JSONObject(
Map.of("name", new JSONString("b"),
"id", new JSONNumber(4)))))));

switch (Service.Of(j)) {
case Service(String name, int id):
System.out.println("Service name: " + name);
break;
default:
throw new IllegalStateException("Unexpected value: " + j);
private static <T> void assertEquals(T expected, T actual) {
if (!Objects.equals(expected, actual)) {
throw new AssertionError("Expected: " + expected + ", but got: " + actual);
}
}
}

0 comments on commit 1ecb187

Please sign in to comment.