Strange pattern matching behaviour with AnyRef

前端 未结 1 2166
悲哀的现实
悲哀的现实 2021-02-20 04:49
def test1(a: Any) = a match {
  case x: AnyRef => \"AnyRef\"
  case _ => \"None of the above\"
}

def test2(a: Any) = a match {
  case x: Double if x > 2 =>          


        
1条回答
  •  逝去的感伤
    2021-02-20 05:23

    This is because Any is actually just an Object. Having Double there is a convenient fiction--it's actually java.lang.Double which is autounboxed for you in the match statement. Unfortunately, there is no way for Scala to tell if it finds a java.lang.Double if it is supposed to be interpreted as a Double or as a java.lang.Double--in the latter case, the AnyRef should catch it. So it does. But if you specifically ask for a Double, it knows it is supposed to unbox, and then the AnyRef case need not be checked. (And, in fact, if you intended it to be a java.lang.Double, it will unbox that too--it can't tell the difference.)

    Whether this is ideal behavior is debatable, but it is logical.

    0 讨论(0)
提交回复
热议问题