Skip to content
TheChatArchiveThe Chat Archive
gpt-4-1106-preview· openaiHugging Face Suzhen/CodeChat

write a complete and functional Scala program using Akka which performs an infinite…

  1. User

    write a complete and functional Scala program using Akka which performs an infinite series of ping-pong messages between 2 actors, with one new message every second.

  2. Assistant

    Below is a complete Scala program that uses Akka to create an infinite ping-pong message exchange between two actors. The program creates two actors: PingActor and PongActor. The PingActor sends a "Ping" message to PongActor, and PongActor responds with a "Pong" message. A new message is sent every second using the Akka scheduler.

    To run this, you need to have the Akka library dependencies included in your build.sbt or build tools configuration.

    import akka.actor.{Actor, ActorRef, ActorSystem, Props}
    import scala.concurrent.duration._
    
    // Define the messages
    case object Ping
    case object Pong
    case object Start
    
    // Define the Ping actor
    class PingActor(pongActor: ActorRef) extends Actor {
      import context.dispatcher // Import the dispatcher for scheduling
    
      def receive: Receive = {
        case Start =>
          println("Ping: Start ping-pong")
          context.system.scheduler.scheduleWithFixedDelay(Duration.Zero, 1.second, pongActor, Ping)
        case Pong =>
          println("Ping: Received Pong")
      }
    }
    
    // Define the Pong actor
    class PongActor extends Actor {
      def receive: Receive = {
        case Ping =>
          println("Pong: Received Ping")
          sender() ! Pong
      }
    }
    
    // Create the ActorSystem
    object PingPongApp extends App {
      val system = ActorSystem("PingPongSystem")
    
      // Create the Pong actor
      val pongActor = system.actorOf(Props[PongActor], name = "pongActor")
    
      // Create the Ping actor
      val pingActor = system.actorOf(Props(new PingActor(pongActor)), name = "pingActor")
    
      // Start the ping-pong exchange
      pingActor ! Start
    }
    

    Make sure to add the necessary Akka dependencies in your build.sbt file:

    libraryDependencies ++= Seq(
      "com.typesafe.akka" %% "akka-actor" % "2.6.18"
    )
    

    When the above program is run, you will see an infinite series of "Ping: Received Pong" and "Pong: Received Ping" messages printed to the console every second.

    Do note that running an infinite loop on the main thread may not be advisable for a real application. You might want to include control mechanisms such as signals to gracefully shut down the actor system and the application.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.