我是Scala和Akka的新手,并且一直在关注本教程.我遇到了以下内容,并想知道这个语法到底意味着什么?
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")
Run Code Online (Sandbox Code Playgroud)
我不确定该评论的内容//Not sure what this means是什么?它似乎是一个通用的特性,它提供了参数化类型.如果我查看源代码,akka.actor.Props则定义为Object扩展特征 AbstractProps.但是,AbstractProps未定义类型参数ie AbstractProps[T].有人可以解释一下这条线是如何工作的,它的作用是什么?
在Scala中,任何实现apply方法的对象都可以在没有new关键字的情况下调用MyObject(),只需通过调用,它将自动查找它apply.
如果你看一下同伴的对象为Props,你会看到定义了以下方法:
/**
* 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)
Run Code Online (Sandbox Code Playgroud)
这apply需要一个类型参数而没有参数.T <: Actor意味着T你要传递的类型必须延伸Actor.这就是Scala知道如何创建对象的方式.
此外,在Scala中使用arity-0的任何方法都可能会删除它的括号.这就是你看到Props[MyActor]实际编译的方式,因为它相当于Props[MyActor](),相当于Props.apply[MyActor]().