Scala pattern matching confusion with Option[Any]

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

    Any information about type parameters is only available at compile-time, not at runtime (this is known as type erasure). This means that at runtime there is no difference between Option[String] and Option[Int], so any pattern matching on the type Option[String], will also match Option[Int] because at runtime both is just Option.

    Since this is almost always not what you intend, you get a warning. The only way to avoid the warning is not to check the generic type of something at runtime (which is fine because that doesn't work like you want it to anyway).

    There is no way to check whether an Option is an Option[Int] or an Option[String] at runtime (other than inspecting the content if it's a Some).

提交回复
热议问题