bind instanceof to named variables (#2088)

* bind instanceof to named variables

* Update StashJavaAPITestActors.java

* Update InteractionPatternsTest.java
This commit is contained in:
PJ Fanning 2025-08-25 13:44:38 +01:00 committed by GitHub
parent 5a7f7d2625
commit 18d7ff815a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
14 changed files with 54 additions and 67 deletions

View file

@ -66,9 +66,10 @@ public class AsyncTestingExampleTest
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;
if (!(o instanceof Pong)) return false; if (o instanceof Pong pong) {
Pong pong = (Pong) o; return message.equals(pong.message);
return message.equals(pong.message); }
return false;
} }
@Override @Override

View file

@ -23,9 +23,9 @@ public class StashJavaAPITestActors {
*/ */
private static int testReceive( private static int testReceive(
Object msg, int count, ActorRef sender, ActorRef self, UnrestrictedStash stash) { Object msg, int count, ActorRef sender, ActorRef self, UnrestrictedStash stash) {
if (msg instanceof String) { if (msg instanceof String s) {
if (count < 0) { if (count < 0) {
sender.tell(((String) msg).length(), self); sender.tell(s.length(), self);
} else if (count == 2) { } else if (count == 2) {
stash.unstashAll(); stash.unstashAll();
return -1; return -1;
@ -33,9 +33,8 @@ public class StashJavaAPITestActors {
stash.stash(); stash.stash();
return count + 1; return count + 1;
} }
} else if (msg instanceof Integer) { } else if (msg instanceof Integer value) {
int value = (Integer) msg; assertEquals(5, value.intValue());
assertEquals(5, value);
} }
return count; return count;
} }

View file

@ -191,11 +191,9 @@ public class AggregatorTest extends JUnitSuite {
r -> { r -> {
// The hotels have different protocols with different replies, // The hotels have different protocols with different replies,
// convert them to `HotelCustomer.Quote` that this actor understands. // convert them to `HotelCustomer.Quote` that this actor understands.
if (r instanceof Hotel1.Quote) { if (r instanceof Hotel1.Quote q) {
Hotel1.Quote q = (Hotel1.Quote) r;
return new Quote(q.hotel, q.price); return new Quote(q.hotel, q.price);
} else if (r instanceof Hotel2.Price) { } else if (r instanceof Hotel2.Price p) {
Hotel2.Price p = (Hotel2.Price) r;
return new Quote(p.hotel, p.price); return new Quote(p.hotel, p.price);
} else { } else {
throw new IllegalArgumentException("Unknown reply " + r); throw new IllegalArgumentException("Unknown reply " + r);

View file

@ -220,14 +220,11 @@ public class InteractionPatternsTest extends JUnitSuite {
private Behavior<Command> onWrappedBackendResponse(WrappedBackendResponse wrapped) { private Behavior<Command> onWrappedBackendResponse(WrappedBackendResponse wrapped) {
Backend.Response response = wrapped.response; Backend.Response response = wrapped.response;
if (response instanceof Backend.JobStarted) { if (response instanceof Backend.JobStarted rsp) {
Backend.JobStarted rsp = (Backend.JobStarted) response;
getContext().getLog().info("Started {}", rsp.taskId); getContext().getLog().info("Started {}", rsp.taskId);
} else if (response instanceof Backend.JobProgress) { } else if (response instanceof Backend.JobProgress rsp) {
Backend.JobProgress rsp = (Backend.JobProgress) response;
getContext().getLog().info("Progress {}", rsp.taskId); getContext().getLog().info("Progress {}", rsp.taskId);
} else if (response instanceof Backend.JobCompleted) { } else if (response instanceof Backend.JobCompleted rsp) {
Backend.JobCompleted rsp = (Backend.JobCompleted) response;
getContext().getLog().info("Completed {}", rsp.taskId); getContext().getLog().info("Completed {}", rsp.taskId);
inProgress.get(rsp.taskId).tell(rsp.result); inProgress.get(rsp.taskId).tell(rsp.result);
inProgress.remove(rsp.taskId); inProgress.remove(rsp.taskId);
@ -712,11 +709,10 @@ public class InteractionPatternsTest extends JUnitSuite {
result.whenComplete( result.whenComplete(
(reply, failure) -> { (reply, failure) -> {
if (reply instanceof CookieFabric.Cookies) if (reply instanceof CookieFabric.Cookies cookiesReply)
System.out.println("Yay, " + ((CookieFabric.Cookies) reply).count + " cookies!"); System.out.println("Yay, " + cookiesReply.count + " cookies!");
else if (reply instanceof CookieFabric.InvalidRequest) else if (reply instanceof CookieFabric.InvalidRequest invalidRequest)
System.out.println( System.out.println("No cookies for me. " + invalidRequest.reason);
"No cookies for me. " + ((CookieFabric.InvalidRequest) reply).reason);
else System.out.println("Boo! didn't get cookies in time. " + failure); else System.out.println("Boo! didn't get cookies in time. " + failure);
}); });
} }
@ -736,12 +732,12 @@ public class InteractionPatternsTest extends JUnitSuite {
CompletionStage<CookieFabric.Cookies> cookies = CompletionStage<CookieFabric.Cookies> cookies =
result.thenCompose( result.thenCompose(
(CookieFabric.Reply reply) -> { (CookieFabric.Reply reply) -> {
if (reply instanceof CookieFabric.Cookies) { if (reply instanceof CookieFabric.Cookies cookiesReply) {
return CompletableFuture.completedFuture((CookieFabric.Cookies) reply); return CompletableFuture.completedFuture(cookiesReply);
} else if (reply instanceof CookieFabric.InvalidRequest) { } else if (reply instanceof CookieFabric.InvalidRequest invalidRequest) {
CompletableFuture<CookieFabric.Cookies> failed = new CompletableFuture<>(); CompletableFuture<CookieFabric.Cookies> failed = new CompletableFuture<>();
failed.completeExceptionally( failed.completeExceptionally(
new IllegalArgumentException(((CookieFabric.InvalidRequest) reply).reason)); new IllegalArgumentException(invalidRequest.reason));
return failed; return failed;
} else { } else {
throw new IllegalStateException("Unexpected reply: " + reply.getClass()); throw new IllegalStateException("Unexpected reply: " + reply.getClass());

View file

@ -169,8 +169,8 @@ interface StashDocSample {
private static RuntimeException asRuntimeException(Throwable t) { private static RuntimeException asRuntimeException(Throwable t) {
// can't throw Throwable in lambdas // can't throw Throwable in lambdas
if (t instanceof RuntimeException) { if (t instanceof RuntimeException runtimeException) {
return (RuntimeException) t; return runtimeException;
} else { } else {
return new RuntimeException(t); return new RuntimeException(t);
} }

View file

@ -117,12 +117,11 @@ public class ActorCompile {
{ {
Behaviors.<MyMsg>receive( Behaviors.<MyMsg>receive(
(context, message) -> { (context, message) -> {
if (message instanceof MyMsgA) { if (message instanceof MyMsgA msgA) {
return Behaviors.receive( return Behaviors.receive(
(ctx2, msg2) -> { (ctx2, msg2) -> {
if (msg2 instanceof MyMsgB) { if (msg2 instanceof MyMsgB msgB) {
((MyMsgA) message).replyTo.tell(((MyMsgB) msg2).greeting); msgA.replyTo.tell(msgB.greeting);
ActorRef<String> adapter = ActorRef<String> adapter =
ctx2.messageAdapter(String.class, s -> new MyMsgB(s.toUpperCase())); ctx2.messageAdapter(String.class, s -> new MyMsgB(s.toUpperCase()));
} }

View file

@ -236,14 +236,14 @@ public class AdapterTest extends JUnitSuite {
static Behavior<Typed2Msg> typed2() { static Behavior<Typed2Msg> typed2() {
return Behaviors.receive( return Behaviors.receive(
(context, message) -> { (context, message) -> {
if (message instanceof Ping) { if (message instanceof Ping ping) {
ActorRef<String> replyTo = ((Ping) message).replyTo; ActorRef<String> replyTo = ping.replyTo;
replyTo.tell("pong"); replyTo.tell("pong");
return same(); return same();
} else if (message instanceof StopIt) { } else if (message instanceof StopIt) {
return stopped(); return stopped();
} else if (message instanceof ThrowIt) { } else if (message instanceof ThrowIt throwIt) {
throw (ThrowIt) message; throw throwIt;
} else { } else {
return unhandled(); return unhandled();
} }

View file

@ -57,16 +57,14 @@ public class FSMStateFunctionBuilder<S, D> {
public boolean test(FSM.Event e) { public boolean test(FSM.Event e) {
boolean res = true; boolean res = true;
if (eventOrType != null) { if (eventOrType != null) {
if (eventOrType instanceof Class) { if (eventOrType instanceof Class eventType) {
Class eventType = (Class) eventOrType;
res = eventType.isInstance(e.event()); res = eventType.isInstance(e.event());
} else { } else {
res = eventOrType.equals(e.event()); res = eventOrType.equals(e.event());
} }
} }
if (res && dataOrType != null) { if (res && dataOrType != null) {
if (dataOrType instanceof Class) { if (dataOrType instanceof Class dataType) {
Class dataType = (Class) dataOrType;
res = dataType.isInstance(e.stateData()); res = dataType.isInstance(e.stateData());
} else { } else {
res = dataOrType.equals(e.stateData()); res = dataOrType.equals(e.stateData());
@ -191,8 +189,7 @@ public class FSMStateFunctionBuilder<S, D> {
boolean emMatch = false; boolean emMatch = false;
Object event = e.event(); Object event = e.event();
for (Object em : eventMatches) { for (Object em : eventMatches) {
if (em instanceof Class) { if (em instanceof Class emc) {
Class emc = (Class) em;
emMatch = emc.isInstance(event); emMatch = emc.isInstance(event);
} else { } else {
emMatch = event.equals(em); emMatch = event.equals(em);

View file

@ -67,16 +67,14 @@ public class FSMStateFunctionBuilder<S, D, E> {
public boolean test(org.apache.pekko.persistence.fsm.PersistentFSM.Event e) { public boolean test(org.apache.pekko.persistence.fsm.PersistentFSM.Event e) {
boolean res = true; boolean res = true;
if (eventOrType != null) { if (eventOrType != null) {
if (eventOrType instanceof Class) { if (eventOrType instanceof Class eventType) {
Class eventType = (Class) eventOrType;
res = eventType.isInstance(e.event()); res = eventType.isInstance(e.event());
} else { } else {
res = eventOrType.equals(e.event()); res = eventOrType.equals(e.event());
} }
} }
if (res && dataOrType != null) { if (res && dataOrType != null) {
if (dataOrType instanceof Class) { if (dataOrType instanceof Class dataType) {
Class dataType = (Class) dataOrType;
res = dataType.isInstance(e.stateData()); res = dataType.isInstance(e.stateData());
} else { } else {
res = dataOrType.equals(e.stateData()); res = dataOrType.equals(e.stateData());
@ -208,8 +206,7 @@ public class FSMStateFunctionBuilder<S, D, E> {
boolean emMatch = false; boolean emMatch = false;
Object event = e.event(); Object event = e.event();
for (Object em : eventMatches) { for (Object em : eventMatches) {
if (em instanceof Class) { if (em instanceof Class emc) {
Class emc = (Class) em;
emMatch = emc.isInstance(event); emMatch = emc.isInstance(event);
} else { } else {
emMatch = event.equals(em); emMatch = event.equals(em);

View file

@ -301,8 +301,8 @@ public class AbstractPersistentFSMTest {
// #customer-apply-event // #customer-apply-event
@Override @Override
public ShoppingCart applyEvent(DomainEvent event, ShoppingCart currentData) { public ShoppingCart applyEvent(DomainEvent event, ShoppingCart currentData) {
if (event instanceof ItemAdded) { if (event instanceof ItemAdded itemAdded) {
currentData.addItem(((ItemAdded) event).getItem()); currentData.addItem(itemAdded.getItem());
return currentData; return currentData;
} else if (event instanceof OrderExecuted) { } else if (event instanceof OrderExecuted) {
return currentData; return currentData;

View file

@ -163,23 +163,23 @@ public class CountMinSketch {
// this is not cryptographic one, anything which is stable and random is good enough // this is not cryptographic one, anything which is stable and random is good enough
return o.hashCode(); return o.hashCode();
} }
if (o instanceof String) { if (o instanceof String s) {
return hash(((String) o).getBytes()); return hash(s.getBytes());
} }
if (o instanceof Long) { if (o instanceof Long l) {
return hashLong((Long) o, 0); return hashLong(l, 0);
} }
if (o instanceof Integer) { if (o instanceof Integer i) {
return hashLong((Integer) o, 0); return hashLong(i, 0);
} }
if (o instanceof Double) { if (o instanceof Double d) {
return hashLong(Double.doubleToRawLongBits((Double) o), 0); return hashLong(Double.doubleToRawLongBits(d), 0);
} }
if (o instanceof Float) { if (o instanceof Float f) {
return hashLong(Float.floatToRawIntBits((Float) o), 0); return hashLong(Float.floatToRawIntBits((Float) o), 0);
} }
if (o instanceof byte[]) { if (o instanceof byte[] array) {
return bytesHash((byte[]) o, 0); return bytesHash(array, 0);
} }
return hash(o.toString()); return hash(o.toString());
} }

View file

@ -57,7 +57,7 @@ public class ActorSourceExample {
final Source<Protocol, ActorRef<Protocol>> source = final Source<Protocol, ActorRef<Protocol>> source =
ActorSource.actorRef( ActorSource.actorRef(
(m) -> m instanceof Complete, (m) -> m instanceof Complete,
(m) -> (m instanceof Fail) ? Optional.of(((Fail) m).ex) : Optional.empty(), (m) -> (m instanceof Fail fail) ? Optional.of(fail.ex) : Optional.empty(),
8, 8,
OverflowStrategy.fail()); OverflowStrategy.fail());
@ -66,8 +66,8 @@ public class ActorSourceExample {
.collect( .collect(
new JavaPartialFunction<Protocol, String>() { new JavaPartialFunction<Protocol, String>() {
public String apply(Protocol p, boolean isCheck) { public String apply(Protocol p, boolean isCheck) {
if (p instanceof Message) { if (p instanceof Message message) {
return ((Message) p).msg; return message.msg;
} else { } else {
throw noMatch(); throw noMatch();
} }

View file

@ -89,7 +89,7 @@ class StreamFeeder extends AbstractBehavior<StreamFeeder.Emitted> {
else return Optional.empty(); else return Optional.empty();
}, },
(msg) -> { (msg) -> {
if (msg instanceof FailureOccured) return Optional.of(((FailureOccured) msg).ex); if (msg instanceof FailureOccured failure) return Optional.of(failure.ex);
else return Optional.empty(); else return Optional.empty();
}); });

View file

@ -69,7 +69,7 @@ public class ActorSourceSinkCompileTest {
{ {
ActorSource.actorRef( ActorSource.actorRef(
(m) -> false, (m) -> false,
(m) -> (m instanceof Failure) ? Optional.of(((Failure) m).ex) : Optional.empty(), (m) -> (m instanceof Failure failure) ? Optional.of(failure.ex) : Optional.empty(),
10, 10,
OverflowStrategy.dropBuffer()) OverflowStrategy.dropBuffer())
.to(Sink.seq()); .to(Sink.seq());