Chihjui Li
Chihjui Li

Reputation: 23

How to use Class in Scala

I want to write some function that can return different Class objects according to the arguments.

For example, I have some classes that extends akka Actor, and I want to get their classes by passing different Int values. The code below is not correct, but I think you can understand what I mean:

def createActor(num: Int): Unit {
  val c: Class = o.getActorClass(num)
  system.actorOf(Props[c]) ! "hello"
}

object o {
  val m: Map[Int, Class] = Map(1->classOf[Actor1], 2->classOf[Actor2])
  def getActorClass(num: Int): Class {
    m(num)
  } 
}

Hope my question is understandable. Thank you!

Upvotes: 0

Views: 101

Answers (2)

Rich Henry
Rich Henry

Reputation: 1849

I would create a generator method for creating a new mapping under a given actor system like so:

def newMapping(sys: ActorSystem, mappings: (Int, Props)*) = {
  assert(sys != null)
  val m = mappings.toMap
  (i: Int) => sys.actorOf(m(i))
}

Then you can create different mappings with different ActorSystems and ultimately get the effect you desire:

val sys = ActorSystem("sys1")
val myMapping = newMapping(sys, 1 -> Props[Class1], 2 -> Props[Class2])

val actor1 = myMapping(1)
val actor2 = myMapping(2)

Upvotes: 0

Till Rohrmann
Till Rohrmann

Reputation: 13346

If you simply return the ActorRef, you should be fine.

def createActor(num: Int): ActorRef = {
  val c = o.getActorClass(num)
  val actor = system.actorOf(Props(c))
  actor ! "hello"
  actor
}

Upvotes: 1

Related Questions