Scala pattern matching confusion with Option[Any]

前端 未结 3 1260
天命终不由人
天命终不由人 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:27

    As already stated, you're up against erasure here.

    For the solution... It's normal with Scala actor to define case classes for each message type you're likely to send:

    case class MessageTypeA(s : String)
    case class MessageTypeB(i : Int)
    
    object Alice extends Actor {
      this.start
      def act{
        loop{
          react {
            case "Hello" => sender ! MessageTypeA("Hi")
            case i:Int => sender ! MessageTypeB(0)
          }
        }
      }
    }
    object Test {
      def test = {
        (Alice !? (100, "Hello")) match {
          case Some(MessageTypeB(i)) => println ("Int received "+i)
          case Some(MessageTypeA(s)) => println ("String received "+s)
          case _ =>
        }
        (Alice !? (100, 1)) match {
          case Some(MessageTypeB(i)) => println ("Int received " + i)
          case Some(MessageTypeA(s)) => println ("String received " + s)
          case _ =>
        }
      }
    }
    

提交回复
热议问题