我有以下的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