简体   繁体   English

在Scala中,一切都是对象-类是对象吗?

[英]In Scala EVERYTHING is an Object - are Classes Objects?

I recently ran into the scala.reflect.runtime API and tried to generate Classdefinitins by Stringevaluation. 我最近遇到了scala.reflect.runtime API,并尝试通过Stringevaluation生成Classdefinitins。 Here is the aproach i made in the scala REPL: 这是我在scala REPL中提出的方法:

scala> import scala.reflect.runtime._
import scala.reflect.runtime._

scala> val cm = universe.runtimeMirror(getClass.getClassLoader)
cm: reflect.runtime.universe.Mirror = JavaMirror with scala.tools.n[....]

scala> import scala.tools.reflect.ToolBox
import scala.tools.reflect.ToolBox

scala> val tb = cm.mkToolBox()
tb: scala.tools.reflect.ToolBox[reflect.runtime.universe.type] = scala.to[...]

scala> tb.eval(tb.parse("class A; scala.reflect.classTag[A].runtimeClass"))
res0: Any = class __wrapper$1$c6a9fb3f39c2499a9ff6e29384816f58.__wrapper$[...]

Since the answer by the REPL is not: 由于REPL的答案不是:

defined class A 定义的A级

but

res0: Any = class __wrapper$1$c6a9fb3f39c2499a9ff6e29384816f58.__wrapper$[...] res0:任意=类__wrapper $ 1 $ c6a9fb3f39c2499a9ff6e29384816f58 .__ wrapper $ [...]

I started to wonder if i actually created a class or kind of just initialized an abstract Any instance? 我开始怀疑我是实际上创建了一个类还是只是初始化了一个抽象的任何实例? I once read that in scala EVERYTHING is an object. 我曾经读过在Scala中,一切都是对象。 If res0 in my REPL now actually holds a class, then this would mean, that even classes are objects in scala? 如果我的REPL中的res0现在实际上拥有一个类,那么这意味着,即使类也是scala中的对象? But this is where i cant find any more input so im really confused. 但这是我找不到更多输入的地方,所以我真的很困惑。 If classes are not objects in scala then what does res0 actually hold at this moment? 如果类不是Scala中的对象,那么res0目前实际持有什么? Thanks in advance for any help. 在此先感谢您的帮助。

No, classes are not objects in a strict sense, neither are methods. 不,从严格意义上讲,类不是对象,方法也不是。 Scala runs on the JVM and Scala classes and methods compile down to the concepts of the JVM. Scala在JVM上运行,Scala类和方法可编译为JVM的概念。

What is usually meant by "everything is an object" is every value is an object, ie native values, instances, functions. 通常所说的“一切都是对象”是每个值都是一个对象,即本机值,实例,函数。

However, there are objects that give you access to the meta information of classes and methods. 但是,有些对象使您可以访问类和方法的元信息。 If you do this 如果你这样做

res0.getClass

You will see, that res0 is an instance of the (Java) class Class. 您将看到res0是(Java)类Class的实例。 So you just have gotten an object from the JVM reflection API. 因此,您只是从JVM反射API获得了一个对象。

The REPL does not give you a "defined class A" because you have defined it in an other context. REPL没有为您提供“已定义的类A”,因为您已在其他上下文中对其进行了定义。

By the way, instead of scala.reflect.classTag[A].runtimeClass you could have just written classOf[A] . 顺便说一句,您可以只编写classOf[A]来代替scala.reflect.classTag[A].runtimeClass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM