我有以下的Scala代码。斯卡拉模式匹配混淆选项[任何]
import scala.actors.Actor
object Alice extends Actor {
this.start
def act{
loop{
react {
case "Hello" => sender ! "Hi"
case i:Int => sender ! 0
}
}
}
}
object Test {
def test = {
(Alice !? (100, "Hello")) match {
case i:Some[Int] => println ("Int received "+i)
case s:Some[String] => println ("String received "+s)
case _ =>
}
(Alice !? (100, 1)) match {
case i:Some[Int] => println ("Int received "+i)
case s:Some[String] => println ("String received "+s)
case _ =>
}
}
}
做Test.test
后,我得到的输出:
scala> Test.test
Int received Some(Hi)
Int received Some(0)
我期待输出
String received Some(Hi)
Int received Some(0)
有什么解释?
作为第二个问题,我得到unchecked
警告上述如下:
C:\scalac -unchecked a.scala
a.scala:17: warning: non variable type-argument Int in type pattern Some[Int] is unchecked since it is eliminated by erasure
case i:Some[Int] => println ("Int received "+i)
^
a.scala:18: warning: non variable type-argument String in type pattern Some[String] is unchecked since it is eliminated by erasure
case s:Some[String] => println ("String received "+s)
^
a.scala:22: warning: non variable type-argument Int in type pattern Some[Int] is unchecked since it is eliminated by erasure
case i:Some[Int] => println ("Int received "+i)
^
a.scala:23: warning: non variable type-argument String in type pattern Some[String] is unchecked since it is eliminated by erasure
case s:Some[String] => println ("String received "+s)
^
four warnings found
我怎样才能避免警告?
编辑:谢谢你的建议。丹尼尔的想法是好的,但似乎并没有与泛型类型的工作,如下面
def test[T] = (Alice !? (100, "Hello")) match {
case Some(i: Int) => println ("Int received "+i)
case Some(t: T) => println ("T received ")
case _ =>
}
的例子以下
错误遇到
警告:warning: abstract type T in type pattern T is unchecked since it is eliminated by erasure
谢谢!其他答案也很好,包括Kevin提出的解决方法。但是,这似乎是修复我的代码没有太多重写的最优雅的方式。 – Jus12 2010-09-24 17:13:45
你能为类属类型提出一个类似的解决方法吗?如: 'def test [T] =(Alice!?(100,“Hello”))match {case Some(t:T)=> println(“T received”); case _ => println(“别的东西收到”)}' – Jus12 2010-09-25 15:03:11
@ Jus12这种方式是行不通的。你需要得到一个'm:Manifest [T]',然后如果m.erasure.isAssignableFrom(t.getClass())=>'做一些事情,如'Some Some(t:T)。 – 2010-09-25 20:50:29