user3077915
user3077915

Reputation: 29

value actorOf is not a member of object akka.actor.Actor

I tried to compile this piece of code to get an idea of how actors really work but it is giving me an error message: value actorOf is not a member of object akka.actor.Actor

I am new to akka and can't actually understand of how to start and know the structure of implementing a whole definition such as the receive method of each class. Also, what is the actual job of ActorLogging? Can anyone help please? Thanks.

import akka.actor.Actor

case object Start

object Main {
  def main(args: Array[String]): Unit = {
    println("Start");
    val echo = Actor.actorOf[EchoActor]
    echo.start()
    echo ! "Hello World"
    echo.stop()
  }
}
class EchoActor extends Actor {
  def receive = {
    case s: String => println(s)
  }
}

Upvotes: 2

Views: 2340

Answers (2)

Dan Simon
Dan Simon

Reputation: 13137

Looks like you're trying to use (I think) Akka 1.x era code with Akka 2.x. Some of the semantics are quite different. Here is one way to correctly implement it:

import akka.actor._

object Main {
  def main(args: Array[String]) {
    println("Start");
    val system = ActorSystem("hello-world")
    val echo = system.actorOf(Props[EchoActor])
    echo ! "Hello World"
    echo ! PoisonPill
  }
}

class EchoActor extends Actor with ActorLogging {
  override def preStart() {
    log.info("starting actor")
  }
  def receive = {
    case s: String => log.info(s)
  }
  override def postStop() {
    log.info("stopping actor")
    context.system.shutdown
  }
}

Basically, you need to use an actor system to create actors, which no longer need to be explicitly started. Sending messages works the same way. To stop an actor, you send it the PoisonPill object, which will cause the actor to immediately shutdown as soon as it gets to the message in its mailbox.

Also, I added a post-stop hook to the actor to shutdown the system when the actor is stopped, otherwise the application will never exit.

The ActorLogging trait allows you to easily hook up actors to Akka's logging framework. When you mix it into an actor, you get a log that you can use like a regular logger.

Upvotes: 3

psisoyev
psisoyev

Reputation: 2168

You probably need to check Akka documentation firstly. Here is the link: http://doc.akka.io/docs/akka/snapshot/scala/actors.html

What you'd like to do is:

import akka.actor.ActorSystem

// ActorSystem is a heavy object: create only one per application
val system = ActorSystem("mySystem")
val myActor = system.actorOf(Props[MyActor], "myactor2")

(took from docs)

So first of all you create an Actor system, and you should use the system to create the actor.

Upvotes: 0

Related Questions