Scala pattern matching confusion with Option[Any] -
Scala pattern matching confusion with Option[Any] -
i have next scala code.
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 _ => } } }
after doing test.test
, output:
scala> test.test int received some(hi) int received some(0)
i expecting output
string received some(hi) int received some(0)
what explanation?
as sec question, unchecked
warnings above follows:
c:\scalac -unchecked a.scala a.scala:17: warning: non variable type-argument int in type pattern some[int] unchecked since eliminated erasure case i:some[int] => println ("int received "+i) ^ a.scala:18: warning: non variable type-argument string in type pattern some[string] unchecked since eliminated erasure case s:some[string] => println ("string received "+s) ^ a.scala:22: warning: non variable type-argument int in type pattern some[int] unchecked since eliminated erasure case i:some[int] => println ("int received "+i) ^ a.scala:23: warning: non variable type-argument string in type pattern some[string] unchecked since eliminated erasure case s:some[string] => println ("string received "+s) ^ 4 warnings found
how can avoid warnings?
edit: suggestions. daniel's thought nice not seem work generic types, in illustration below
def test[t] = (alice !? (100, "hello")) match { case some(i: int) => println ("int received "+i) case some(t: t) => println ("t received ") case _ => }
the next error warning encountered: warning: abstract type t in type pattern t unchecked since eliminated erasure
this due type-erasure. jvm not know of type parameter, except on arrays. because of that, scala code can't check whether option
option[int]
or option[string]
-- info has been erased.
you prepare code way, though:
object test { def test = { (alice !? (100, "hello")) match { case some(i: int) => println ("int received "+i) case some(s: string) => println ("string received "+s) case _ => } (alice !? (100, 1)) match { case some(i: int) => println ("int received "+i) case some(s: string) => println ("string received "+s) case _ => } } }
this way not testing type of option
is, type of contents -- assuming there content. none
fall through default case.
scala pattern-matching actor unchecked
Comments
Post a Comment