2016-05-08 80 views
4

我是Scala和Akka的新手,並且一直遵循this教程。我遇到以下問題,並想知道這個語法的意思是什麼?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") 

我不確定哪一行用//Not sure what this means註釋過嗎?這似乎是一個通用的特徵,給出了參數化的類型。如果我看看source codeakka.actor.Props被定義爲Object,它擴展了traitAbstractProps。但是,AbstractProps沒有用類型參數定義,即AbstractProps[T]。有人能解釋上面的線路是如何工作的嗎?

+0

另外,要小心這個:當使用'Props [A]'變種時,要小心這個問題:http://stackoverflow.com/questions/33042105/differences-between-propsnew-a-with-b-and-propsa-with-b。 – ale64bit

回答

6

在Scala中,它實現了apply方法的對象可以在不new叫關鍵字,只需撥打MyObject()即可自動查找apply

如果你看一下companion objectProps,你會看到定義了以下方法:

/** 
* 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) 

apply接受一種類型的參數,沒有爭吵。 T <: Actor表示T,您傳遞的類型必須延伸Actor。這就是Scala知道如何創建對象的方式。

此外,Scala中arity-0的任何方法都可能會捨棄它的括號。這就是你看到Props[MyActor]實際編譯的方式,因爲它相當於Props[MyActor](),相當於Props.apply[MyActor]()

3

akka.actor.Props被定義爲延伸性狀 AbstractProps

其也被定義爲一個情況下類的對象:

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

這是Scala中的一個常見的模式,一個伴侶對象的類。伴侶對象經常包含工廠方法,這就是你在你的例子中實際調用的內容。

val props1 = Props[MyActor] 

這只是調用伴隨對象的apply()。如果不需要任何參數,則可以省略Scala中的括號,並且apply是可以直接在對象/實例上調用的特殊方法。假設你有一個序列和想要的元素索引1:

val s = Seq("one", "two", "three") 
// These two are equivalent 
s(1) // -> "two" 
s.apply(1) // -> "two" 

最終你的代碼可以改寫爲

val props1 = Props.apply[MyActor]()