scala中的模式匹配零参数函数:被警告迷惑
我在玩scala的分布式演员。非常好 我有一个执行传入函数对象的服务器。 例如,客户端具有scala中的模式匹配零参数函数:被警告迷惑,scala,functional-programming,pattern-matching,Scala,Functional Programming,Pattern Matching,我在玩scala的分布式演员。非常好 我有一个执行传入函数对象的服务器。 例如,客户端具有 object Tasks { def foo = {Console.println("I am Foo")}; def bar = {Console.println("I am Bar");} } // In client actor... ... server ! Tasks.foo _ ... 服务器可以提取这些代码,并使用actor代码执行它们,如 react { case ta
object Tasks {
def foo = {Console.println("I am Foo")};
def bar = {Console.println("I am Bar");}
}
// In client actor...
...
server ! Tasks.foo _
...
服务器可以提取这些代码,并使用actor代码执行它们,如
react {
case task:(()=>Unit) =>
task()
这一切都很好(确实非常酷),但我被scalac
为服务器代码输出的警告消息弄糊涂了:
warning: non variable type-argument Unit in type pattern is unchecked since it is eliminated by erasure
case task:(()=>Unit) =>
^
我怎样才能清除这个警告
(我不清楚单位
类型和()=>单位
类型的零参数函数之间的区别。只是尝试匹配任务:反应
中的单位
没有警告,但实际上与传入任务不匹配。)
在Debian上使用Scala 2.7.5,与Sun的Java6配合使用。您真的做到了这一点:
case task:Function0[Unit] => task()
由于擦除,单元在运行时不可见。
如果您真的不关心返回类型,可以在react块中执行此操作:
case task:Function0[_] => task()
这是对他的回答的补充,因为在这种情况下,他的回答会让你通过
您可能需要将(Function0[T],Manifest[T])
的元组传递给参与者。正如您在下面看到的,Scala非常聪明,可以推断出T
的类型,即使您只需编写matchFunction(foo)
scala>def foo={Console.println(“我是foo”)}
傅:单位
scala>导入scala.reflect.Manifest
导入scala.reflect.Manifest
scala>defmatchfunction[T](f:Function0[T])(隐式m:Manifest[T]){
|(m,f)匹配{
|案例(om:Manifest[\u],of:Function0[\u])=>
|if(omt)(隐式scala.reflect.Manifest[T])单位
scala>matchFunction(foo)
我是福
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