2009-10-07 24 views
5

我正在玩scala的分佈式演員。非常好。模式匹配scala中的零參數函數:通過警告迷惑

我有一個服務器執行傳入的函數對象。 例如,客戶端有

object Tasks { 
    def foo = {Console.println("I am Foo")}; 
    def bar = {Console.println("I am Bar");} 
} 

// In client actor... 
... 
    server ! Tasks.foo _ 
... 

和服務器都可以選擇這些並與演員這樣的代碼

react { 
    case task:(()=>Unit) => 
    task() 

這一切工作很好地執行它們(這是非常非常酷確實)但我

warning: non variable type-argument Unit in type pattern is unchecked since it is eliminated by erasure 
     case task:(()=>Unit) => 
        ^

如何清潔此警告了:M通過一條警告消息輸出服務器代碼迷惑通過scalac

(我在Unit類型之間的區別不太清楚,和()=>Unit類型的零參數的函數。只是想在react匹配task:Unit是免費的預警,但實際上不匹配傳入任務)

在Debian上使用Scala 2.7.5,使用Sun的Java6。

回答

10

你真的匹配這樣的:

case task:Function0[Unit] => task() 

由於擦除,單位是不能在運行時可見。 如果你真的不關心的返回類型,你可以在反應塊做到這一點:

case task:Function0[_] => task() 
3

這是補充@Mitch Blevins的答案,因爲他的答案會在這種情況下讓你通過。

請參閱How do I get around type erasure on Scala? Or, why can’t I get the type parameter of my collections?您可能必須將(Function0[T],Manifest[T])的元組傳遞給演員。正如您在下面看到的,即使您只是編寫matchFunction(foo _),Scala也足夠聰明,可以推導出T的類型。

scala> def foo = {Console.println("I am Foo")} 
foo: Unit 

scala> import scala.reflect.Manifest 
import scala.reflect.Manifest 

scala> def matchFunction[T](f: Function0[T])(implicit m : Manifest[T]) { 
    | (m,f) match { 
    |  case (om: Manifest[_],of: Function0[_]) => 
    |  if(om <:< m) { 
    |   of.asInstanceOf[Function0[T]]() 
    |  } 
    | } 
    | } 
matchFunction: [T](() => T)(implicit scala.reflect.Manifest[T])Unit 

scala> matchFunction(foo _) 
I am Foo