为什么 AnyVal 不能用于 isInstanceOf 检查? [英] Why can AnyVal not be used in an isInstanceOf check?

查看:61
本文介绍了为什么 AnyVal 不能用于 isInstanceOf 检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,为什么 AnyVal 不能用于 isInstanceOf 检查?这种行为背后的原因是什么?

I was wondering, why AnyVal can not be used in an isInstanceOf check ? What is the reason behind this behavior ?

scala> val c = 't'
c: Char = t

scala> c.isInstanceOf[AnyVal]
<console>:12: error: type AnyVal cannot be used in a type pattern or isInstanceO
f test
             c.isInstanceOf[AnyVal]

推荐答案

AnyVal 在运行时不再存在.仅在编译时.换句话说,将 JVM 原语视为一流对象只是编译器的技巧".

AnyVal does not exist anymore at runtime. Only at compile-time. In other words, it's just a compiler "trick" to consider the JVM primitives as first-class objects.

然而,isInstanceOf 方法是在运行时执行的,所以它无法工作.因此编译器错误.

However, the isInstanceOf method is executed at runtime, so it cannot work. Hence the compiler error.

这篇关于为什么 AnyVal 不能用于 isInstanceOf 检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆