Hongseok Yoon
Hongseok Yoon

Reputation: 3308

Failed to run simple akka sample using sbt

I'm just following akka sample but could not run the program.

  1. I've installed akka, sbt(0.13), scala(2.10.3) using homebrew(OSX Mountail Lion)
  2. make empty directory named akka_test
  3. create build.sbt and Hello.scala file
  4. run sbt in akka_test directory and compile command worked well
  5. sbt's run command complains No main class detected

What should I do to run the program?

here's my code

build.sbt

name := "My Project"

version := "1.0"

scalaVersion := "2.10.2"

resolvers += "Typesafe Repository" at "http://repo.typesafe.com/typesafe/releases/"

libraryDependencies +=
  "com.typesafe.akka" %% "akka-actor" % "2.2.1"

Hello.scala

import akka.actor.Actor
import akka.actor.Props

class HelloWorld extends Actor {

  override def preStart(): Unit = {
    // create the greeter actor
    val greeter = context.actorOf(Props[Greeter], "greeter")
    // tell it to perform the greeting
    greeter ! Greeter.Greet
  }

  def receive = {
    // when the greeter is done, stop this actor and with it the application
    case Greeter.Done ⇒ context.stop(self)
  }
}

object Greeter {
  case object Greet
  case object Done
}

class Greeter extends Actor {
  def receive = {
    case Greeter.Greet ⇒
      println("Hello World!")
      sender ! Greeter.Done
  }
}

Upvotes: 8

Views: 2591

Answers (3)

Ponimas
Ponimas

Reputation: 166

sbt has run-main command which accepts main class from command line, so full command is

sbt "run-main akka.Main HelloWorld"

Upvotes: 13

kondratx
kondratx

Reputation: 41

in case you have package you need to add the path. For example if you have package com.foo.bar
(your HelloWorld is in ./youProject/src/main/scala/com/foo/bar) then the command will be:

sbt "run-main akka.Main com.foo.bar.HelloWorld"

Upvotes: 4

waffle paradox
waffle paradox

Reputation: 2775

sbt run looks for a "main" class, i.e., a class with def main(args: Array[String]) or extends the trait App. Since that can't be an actor, you'll need to initiate a system and use that to initiate HelloWorld, so something like:

class HelloWorldMain {
    def main(args: Array[String]) {
        import akka.actor.ActorSystem
        val system = ActorSystem("HelloWorld")
        val helloWorldActor = system.actorOf(Props[HelloWorld] ...)
        // ... Do stuff
    }
}

Since systems just run until you shut them down, if you want your main class to stop you'll either have to use futures via akka.pattern.ask and have the system terminate after you collect them or set up a separate reaper actor to kill the system for you. This post has more info on how to do that, and this pull request is a good example of how it looks in practice (and has some other useful stuff in there as well)

Upvotes: 5

Related Questions