Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala/Akka Syntax

Tags:

scala

akka

I'm new to both Scala and Akka and have been following this tutorial. I came across the following and wondering what exactly this syntax does/mean?

import akka.actor.Props

val props1 = Props[MyActor] //Not sure what this means???
val props2 = Props(new ActorWithArgs("arg")) // careful, see below
val props3 = Props(classOf[ActorWithArgs], "arg")

I'm not sure what the line commented with //Not sure what this means does? It seems like a generic trait that gives a parameterised type. If I look at the source code, akka.actor.Props is defined as an Object that extends the trait AbstractProps. However, AbstractProps is not defined with a type parameter i.e. AbstractProps[T]. Can someone explain how that above line works and what it does?

like image 703
MojoJojo Avatar asked Dec 25 '22 06:12

MojoJojo


1 Answers

In Scala, any object which implements an apply method can be called without the new keyword, simply by calling MyObject(), which will automatically lookup for it's apply.

If you look at the companion object for Props, you'll see the following method defined:

/**
 * Scala API: Returns a Props that has default values except for "creator"
 * which will be a function that creates an instance
 * of the supplied type using the default constructor.
 */
def apply[T <: Actor: ClassTag](): Props = 
    apply(defaultDeploy, implicitly[ClassTag[T]].runtimeClass, List.empty)

This apply takes one type parameter and no arguments. T <: Actor means that T, the type you're passing, must extend Actor. That's how Scala knows how to create the object.

Additionally, any method with arity-0 in Scala may drop it's parenthesis. That's how you're seeing Props[MyActor] actually compile, as it is equivalent of Props[MyActor](), which is equivalent to Props.apply[MyActor]().

like image 192
Yuval Itzchakov Avatar answered Jan 09 '23 03:01

Yuval Itzchakov