Channel Directions in Scala

In Scala, we can use Actors to achieve similar functionality to Go’s channels. Here’s how we can implement the channel directions concept:

import akka.actor.{Actor, ActorRef, ActorSystem, Props}

// This PingActor only accepts messages to send.
// It would be a compile-time error to try to receive messages in this actor.
class PingActor(pongs: ActorRef) extends Actor {
  def receive: Receive = {
    case msg: String => pongs ! msg
  }
}

// The PongActor accepts messages to receive and has a reference to send messages.
class PongActor extends Actor {
  def receive: Receive = {
    case msg: String => 
      println(msg)
      context.system.terminate()
  }
}

object ChannelDirections extends App {
  val system = ActorSystem("ChannelDirections")
  
  val pongs = system.actorOf(Props[PongActor], name = "pongActor")
  val pings = system.actorOf(Props(new PingActor(pongs)), name = "pingActor")

  pings ! "passed message"
}

In this Scala example, we’re using Akka Actors to demonstrate the concept of channel directions.

The PingActor is analogous to the ping function in the original example. It only accepts messages to send, which it then forwards to the PongActor.

The PongActor is similar to the pong function. It receives messages and prints them.

In the ChannelDirections object (which is equivalent to the main function), we set up the actor system, create our actors, and send a message.

To run this program, you would need to have Akka in your project dependencies. You can run it using SBT or by compiling and running it directly with Scala.

$ sbt run
passed message

This example demonstrates how Scala, using Akka Actors, can achieve similar functionality to Go’s channel directions. While the syntax and exact mechanisms differ, the concept of controlling the direction of communication remains the same.