Scala pattern matching confusion with Option[Any]

前端 未结 3 1261
天命终不由人
天命终不由人 2021-02-02 07:51

I have the following Scala code.

import scala.actors.Actor

object Alice extends Actor {
  this.start
  def act{
    loop{
      react {
        case \"Hello\" =         


        
3条回答
  •  抹茶落季
    2021-02-02 08:29

    This is due to type-erasure. The JVM does not know of any type parameter, except on arrays. Because of that, Scala code can't check whether an Option is an Option[Int] or an Option[String] -- that information has been erased.

    You could fix your code this 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 you are not testing what the type of Option is, but what the type of its contents are -- assuming there is any content. A None will fall through to the default case.

提交回复
热议问题