What feature of Scala allows the syntax of Props [SomeActor]

One aspect of Akka that I have always been silent about appears right in the canonical Hello World! example. That is, the syntax for creating a class is Props:

val props = Props[MyActor]

Q. What mechanism in Scala allows you to specify a type parameter (ie [MyActor]) in this way? I assume this translates to the constructor / apply method on Props, which takes a parameter Class? For example, I assume this is equivalent to:

val props = Props(classOf[MyActor])

I always assumed that I classOfwas "special" and somehow tricked into using syntax []. Since I see that Akka, a third-party library, uses the same syntax, it would be great to see a simple REPL example demonstrating how I can use this syntax for my own classes.

+4
source share
2 answers

The requisite instances ultimately belong to the following case class ( https://github.com/akka/akka/blob/0511b07f3e50e0422379075ae76dd158e4d377fa/akka-actor/src/main/scala/akka/actor/Props.scala#L115 )

final case class Props(deploy: Deploy, clazz: Class[_], args: immutable.Seq[Any])

Since this is a case class, scala will generate a applydefault method

Props.apply(deploy: Deploy, clazz: Class[_], args: immutable.Seq[Any])

Props apply, , . Props[MyActor] :

def apply[T <: Actor: ClassTag](): Props = apply(defaultDeploy, implicitly[ClassTag[T]].runtimeClass, List.empty)

Props[MyActor] Props.apply[MyActor](). Props ClassTag, MyActor, clazz: Class[_] case Props.

+5

Scala ClassTag. :

object Test {
  def apply[T: ClassTag](s: String): Option[T] = ...
}

val foo = Test[Foo]("foo")

apply -

val ctor = implicitly[ClassTag[T]].runtimeClass.getConstructors.head

T, .

+1

Source: https://habr.com/ru/post/1615189/


All Articles