If scala advocate immutability, why has he adopted the acting model with its fluid nature?

I am new to scala and actor world.

This is what I have learned so far:

Scala is functional programming (not pure) and people advise against using mutable state in scala.

But on the other hand, there is akka framework that implements the actor's model. And while playing with akka, I realized that messages are immutable BUT the state of the actors in MUTABLE. So I need to specify inside the "var" variables and modified collections. And, to me, having mutable state is not natural to scala.

So, is my understanding correct? Why do people accept changed actors in the unchanging scala language?

+3


source to share


3 answers


This is an interesting point, and indeed, actors are very different from the rest of Scala-like code.

You can think of actors as swapping threads with locks, semaphores, and the rest. This is a more intuitive and efficient parallel programming model because mutable state is always encapsulated in an actor that processes messages sequentially.

It provides a solid foundation for creating more functional abstractions. Akka team has produced akka streams. Spark uses akka to communicate across nodes. Future

s, another successful functional alternative to the problem is essentially a special case of streams: a stream of exactly one element and can be implemented using actors.



Thus, people use actors because some problems are solved more intuitively when actors exchange messages with each other than with streaming operations. Since the main argument against mutability is the complete mess it creates on concurrency, and actors decide exactly that, I think it's okay to have this mutability. They are quite complex, but the correct solution for concurrency is actually complex.

And just a side note, threads are arguably a functional way of modeling any interaction between a program and its environment. For example. for GUI development, you could provide all control fired events as a thread, and minimizing the thread essentially creates a way to manage the state of the program.

+9


source


Scala is a language that allows mixed models. Truly, most examples use mutable state inside Actors, but you can use immutable Actors using become

:



class ListActor extends Actor {
  def receive = changeState(List.empty[String])

  def changeState(state: List[String]): Receive = {
    case Add(item) =>
      context.become(changeState(item :: state))
  }
}

      

+3


source


Good question with an interesting answer (IMHO): Scala doesn't work. It's post-functional . This means that it combines object-oriented and functional programming into a single paradigm.

In this framework, Scala maintains immutability, but does not enforce it. The Actor model is one place where mutability makes sense, since all changes are local, the coordination of parallel behavior is done for you by the acting system.

+2


source







All Articles