isInstance 和 isInstanceOf 的区别 [英] Difference between isInstance and isInstanceOf

查看:62
本文介绍了isInstance 和 isInstanceOf 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

classOf[String].isInstance("42")"42".isInstanceOf[String] 有区别吗?

如果是,你能解释一下吗?

If yes, can you explain ?

推荐答案

对于引用类型(那些扩展 AnyRef 的引用类型),最终结果没有区别.然而,isInstanceOf 受到了很大的鼓励,因为它更惯用(并且可能更有效).

For reference types (those that extend AnyRef), there is no difference in the end result. isInstanceOf is however much encouraged, because it's more idiomatic (and likely much more efficient).

对于原始值类型,例如数字和布尔值,是有区别的:

For primitive value types, such as numbers and booleans, there is a difference:

scala> val x: Any = 5
x: Any = 5

scala> x.isInstanceOf[Int]
res0: Boolean = true

scala> classOf[Int].isInstance(x)
res1: Boolean = false

这是因为当向上转换为 Any(或 AnyVal)时,原始值类型被装箱.对于 JVM,它们显示为 java.lang.Integers,而不是 Ints.isInstanceOf 知道这一点并且会做正确的事情.

That is because primitive value types are boxed when upcasted to Any (or AnyVal). For the JVM, they appear as java.lang.Integers, not as Ints anymore. The isInstanceOf knows about this and will do the right thing.

一般来说,如果您知道 T 是什么,就没有理由使用 classOf[T].isInstance(x).如果您有一个泛型类型,并且想要传递"一种方法来测试某个值是否属于该类(将通过 isInstanceOf 测试),则可以使用 scala.改为reflect.ClassTag.ClassTags 有点像 Classes,除了它们了解 Scala 拳击和其他一些东西.(如果需要,我可以详细说明 ClassTag,但您应该在其他地方找到有关它们的信息.)

In general, there is no reason to use classOf[T].isInstance(x) if you know right then what T is. If you have a generic type, and you want to "pass around" a way to test whether a value is of that class (would pass the isInstanceOf test), you can use a scala.reflect.ClassTag instead. ClassTags are a bit like Classes, except they know about Scala boxing and a few other things. (I can elaborate on ClassTags if required, but you should find info about them elsewhere.)

这篇关于isInstance 和 isInstanceOf 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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