Scala
Akka Actors (Pekko)
Message-passing concurrency with the actor model.
By EZ4Code Team
actorakkaconcurrency
Code
import akka.actor.{Actor, ActorSystem, Props}
class Counter extends Actor {
var count = 0
def receive: Receive = {
case "inc" => count += 1
case "get" => sender() ! count
case "reset" => count = 0
}
}
val system = ActorSystem("my-system")
val counter = system.actorOf(Props[Counter](), "counter")
counter ! "inc"
counter ! "inc"
counter ! "get"
// Use ask pattern for async reply:
// val f = counter ? "get"Explanation
Actors encapsulate state and communicate via immutable messages, avoiding shared-memory locks. Akka (now Pekko after the license change) is the canonical implementation. Each actor processes one message at a time, making concurrency safe. Use ? (ask) for request-response, ! (tell) for fire-and-forget.
More Scala Snippets
Pattern Matching
Destructure values and match cases in Scala.
Case Classes
Immutable data classes with auto-generated equals/hashCode/toString.
Collections Operations
Functional collection operations: map, filter, fold, groupBy.
Traits and Mixins
Compose behaviors using traits with default implementations.
Futures and Async
Asynchronous computation with Future and ExecutionContext.
Implicits (Given/Using in Scala 3)
Type-class derivation and context passing via implicits.