Ho il seguente codice Scala.Confusione corrispondenza modello Scala con Option [Any]
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 _ =>
}
}
}
Dopo aver fatto Test.test
, ottengo l'output:
scala> Test.test
Int received Some(Hi)
Int received Some(0)
mi aspettavo l'uscita
String received Some(Hi)
Int received Some(0)
Qual è la spiegazione?
Come una seconda domanda, ottengo unchecked
avvertimenti con quanto sopra come segue:
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
Come posso evitare gli avvertimenti?
EDIT: Grazie per i suggerimenti. L'idea di Daniel è bello, ma non sembra funzionare con tipi generici, come nell'esempio qui sotto
def test[T] = (Alice !? (100, "Hello")) match {
case Some(i: Int) => println ("Int received "+i)
case Some(t: T) => println ("T received ")
case _ =>
}
Il seguente
errore si verifica
avvertimento: warning: abstract type T in type pattern T is unchecked since it is eliminated by erasure
Grazie! Anche le altre risposte sono buone, compresa la soluzione suggerita da Kevin. Ma questo sembra il modo più elegante per sistemare il mio codice senza molto riscrivere. – Jus12
Puoi suggerire una soluzione alternativa simile per i tipi generici? come in: 'def test [T] = (Alice!? (100," Ciao ")) match {case Some (t: T) => println (" T received "); case _ => println ("qualcos'altro ricevuto")} ' – Jus12
@ Jus12 In questo modo non funzionerà. Avrai bisogno di ottenere un 'm: Manifest [T]', quindi fare qualcosa come 'case Some (t: T) se m.erasure.isAssignableFrom (t.getClass()) =>'. –