user3663882 user3663882 - 4 months ago 9
Scala Question

How to understand a Scala's method declaration?

I'm new to Scala and got into troubles with understanding this declaration:

Here's the declaration from

Akka
's
Props
object:

def apply[T <: Actor: ClassTag](): Props = __THE_DEFENITION_GOES_HERE__


Why can we use it like this:

val props = Props[TestActor]


where
class TestActor extends Actor
. I'm curious about how just by
Generic Type
argument, the compiler is able to find the appropriate method defenition. How does it work?

Answer

There is some special magic involved with the apply method in a Scala object. This:

val something = Hello()

is special shortcut syntax for this:

val something = Hello.apply()

Similarly, looking at your example:

val props = Props[TestActor]

is just short syntax for this:

val props = Props.apply[TestActor]()

The [TestActor] is just filling in the type argument for the apply method.

Comments