将元组与 null 匹配
我不明白为什么以下情况不匹配。 Null 应该是 Any 的实例,但它不匹配。有人可以解释发生了什么事吗?
val x = (2, null)
x match {
case (i:Int, v:Any) => println("got tuple %s: %s".format(i, v))
case _ => println("catch all")
}
prints catch all
谢谢。
I don't understand why the following case doesn't match. Null should be an instance of Any, but it doesn't match. Can someone explain what is going on?
val x = (2, null)
x match {
case (i:Int, v:Any) => println("got tuple %s: %s".format(i, v))
case _ => println("catch all")
}
prints catch all
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这与指定的完全一样。
有趣的是,如此多的相关性都归因于 null 作为 Any 的成员。它是除 AnyVal 和 Nothing 之外的所有类型的成员。
This is exactly as specified.
It's interesting that so much relevance has been attributed to null being a member of Any. It's a member of every type but AnyVal and Nothing.
您是否尝试过使用
v
占位符来表示任何内容?Have you tried the
v
placeholder for anything?这是指定的(Scala 参考 2.7,第 8.2 节):
That's as specified (Scala Reference 2.7, section 8.2):
我只是在这里猜测,因为我不是 scala 专家,但根据 scala 中 Any 类的文档 我认为,由于 null 不是一个对象,因此它不是从 Any 派生的,因此与第一个列出的情况不匹配。
添加下面的代码示例。运行时它会打印“其他内容”。
经过更多研究后,似乎 null 应该与 文档 的任何意义相匹配 表示它扩展了 AnyRef,而 AnyRef 又扩展了 Any。
编辑:就像其他人所说的那样。第一种情况故意不匹配 null。它在文档中指定。
I'm just guessing here since I'm no scala expert but according to the documentation for the Any class in scala I'm thinking that since null isn't an object, it doesn't derive from Any and as such doesn't match the first listed case.
Adding the code sample below. It prints "something else" when run.
After more research it seems like null should match with any sense the documentation says that it extends AnyRef which extends Any.
EDIT: Like everyone else has said. The first case doesn't match null on purpose. It's specified in the documentation.