How to have common code for all messages received?

This example using a Trait for Scala is, I think, what would solve my problem: https://coderwall.com/p/np73qw/chaining-akka-actor-receive-methods But I can’t quite figure out how to make it work in Java.

My problem being: I’d like to do some common code for every message received. For instance, if there existed a matchAnyAndKeepGoing() method in receiveBuilder that is what I would be using.

The same mechanism is available for Java (we always aim for 100% feature parity after all);

The blog uses the orElse of Scala’s partial functions which are “apply left OR apply right if the left one did not get applied”. The same capability exists in the Receive type for Java, e.g. inside an AbstractActor you can:

  static class X extends AbstractActor {

    @Override
    public Receive createReceive() {
      Receive hello = receiveBuilder().matchEquals("Hello", s -> sender().tell("world", self())).build();
      Receive normal = receiveBuilder().match(String.class, s ->).build();
      return hello.orElse(normal);
    }
  }

Hi Ktoso,
Thanks very much for answering. Perhaps I misunderstood the Scala example I referenced, but if your solution is reproducing that faithfully, it’s not what I wanted. I added (mostly) your code as this:

    @Override
    public Receive createReceive() {
        Receive hello = receiveBuilder().matchEquals("Hello", s -> sender().tell("world", self())).build();
        Receive normal = receiveBuilder().match(String.class, s -> sender().tell("normal", self())).build();
        return hello.orElse(normal);
    }

And wrote tests for it like this:

    @Test
    public void shouldReturnJustNormal() {
        final TestKit probe = new TestKit(system);
        actorUnderTest.tell("notHello", probe.getRef());
        probe.expectMsg("normal");
    }

    @Test
    public void itWorksLikeThisWhichIsNotWhatIWant() {
        final TestKit probe = new TestKit(system);
        actorUnderTest.tell("Hello", probe.getRef());
        probe.expectMsg("world");
        probe.expectNoMsg();
    }

    @Test
    public void thisShouldReturnWorldThenNormal() {
        final TestKit probe = new TestKit(system);
        actorUnderTest.tell("Hello", probe.getRef());
        probe.expectMsg("world");
        probe.expectMsg("normal");
    }

The 1st and 2nd tests pass, the 3rd does not. So I do have what you said, an XOR type behavior, stopping at the first item whose predicate evals to true, but what I want is to keep going, regardless of the evaluation of a particular match. As if there was a method matchAnyAndKeepGoing().