scala Scala中对象和类之间的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1755345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between object and class in Scala
提问by Steve
I'm just going over some Scala tutorials on the Internet and have noticed in some examples an object is declared at the start of the example.
我刚刚浏览了 Internet 上的一些 Scala 教程,并注意到在一些示例中,在示例的开头声明了一个对象。
What is the difference between classand objectin Scala?
Scalaclass和objectScala 中的区别是什么?
采纳答案by ziggystar
tl;dr
tl;博士
class Cdefines a class, just as in Java or C++.object Ocreates a singletonobjectOas instance of some anonymous class; it can be used to hold static members that are not associated with instances of some class.object O extends Tmakes the objectOan instance oftrait T; you can then passOanywhere, aTis expected.- if there is a
class C, thenobject Cis the companion objectof classC; note that the companion object is notautomatically an instance ofC.
class C定义一个类,就像在 Java 或 C++ 中一样。object O创建一个单例对象O作为某个匿名类的实例;它可用于保存与某个类的实例无关的静态成员。object O extends T使对象O成为 的实例trait T;然后你可以通过O任何地方,aT是预期的。- 如果有
class C,则object C是类的伴生对象C;请注意,伴随对象不会自动成为 的实例C。
Also see Scala documentation for objectand class.
objectas host of static members
object作为静态成员的主机
Most often, you need an objectto hold methods and values/variables that shall be available without having to first instantiate an instance of some class.
This use is closely related to staticmembers in Java.
大多数情况下,您需要object保存方法和值/变量,这些方法和值/变量无需先实例化某个类的实例即可使用。这种用法与staticJava 中的成员密切相关。
object A {
def twice(i: Int): Int = 2*i
}
You can then call above method using A.twice(2).
然后您可以使用A.twice(2).
If twicewere a member of some class A, then you would need to make an instance first:
如果twice是某个 class 的成员A,那么您需要先创建一个实例:
class A() {
def twice(i: Int): Int = 2 * i
}
val a = new A()
a.twice(2)
You can see how redundant this is, as twicedoes not require any instance-specific data.
您可以看到这是多么冗余,因为twice不需要任何特定于实例的数据。
objectas a special named instance
object作为一个特殊的命名实例
You can also use the objectitself as some special instance of a class or trait.
When you do this, your object needs to extend some traitin order to become an instance of a subclass of it.
您还可以将其object本身用作类或特征的一些特殊实例。当你这样做时,你的对象需要扩展一些trait才能成为它的子类的实例。
Consider the following code:
考虑以下代码:
object A extends B with C {
...
}
This declaration first declares an anonymous (inaccessible) class that extends both Band C, and instantiates a single instance of this class named A.
此声明首先声明了一个匿名(不可访问)类,该类扩展了B和C,并实例化了名为 的此类的单个实例A。
This means Acan be passed to functions expecting objects of type Bor C, or B with C.
这意味着A可以传递给需要Bor C、 or类型对象的函数B with C。
Additional Features of object
附加功能 object
There also exist some special features of objects in Scala. I recommend to read the official documentation.
Scala 中还存在对象的一些特殊功能。我建议阅读官方文档。
def apply(...)enables the usual method name-less syntax ofA(...)def unapply(...)allows to create custom pattern matching extractors- if accompanying a class of the same name, the object assumes a special role when resolving implicit parameters
回答by Daniel C. Sobral
A classis a definition, a description. It defines a type in terms of methods and composition of other types.
Aclass是定义,描述。它根据方法和其他类型的组合来定义类型。
An objectis a singleton -- an instance of a class which is guaranteed to be unique. For every objectin the code, an anonymous class is created, which inherits from whatever classes you declared objectto implement. This class cannot be seen from Scala source code -- though you can get at it through reflection.
Anobject是一个单例——一个保证唯一的类的实例。对于object代码中的每一个,都会创建一个匿名类,该类继承自您声明object要实现的任何类。从 Scala 源代码中看不到这个类——尽管您可以通过反射来获得它。
There is a relationship between objectand class. An object is said to be the companion-object of a class if they share the same name. When this happens, each has access to methods of privatevisibility in the other. These methods are not automatically imported, though. You either have to import them explicitly, or prefix them with the class/object name.
object和之间存在关系class。如果对象具有相同的名称,则称它们为类的伴生对象。发生这种情况时,每个人都可以访问private另一个人的可见性方法。但是,这些方法不会自动导入。您要么必须显式导入它们,要么使用类/对象名称作为前缀。
For example:
例如:
class X {
// class X can see private members of object X
// Prefix to call
def m(x: Int) = X.f(x)
// Import and use
import X._
def n(x: Int) = f(x)
private def o = 2
}
object X {
private def f(x: Int) = x * x
// object X can see private members of class X
def g(x: X) = {
import x._
x.o * o // fully specified and imported
}
}
回答by Thomas Jung
An object has exactly oneinstance (you can not call new MyObject). You can have multipleinstances of a class.
一个对象只有一个实例(您不能调用new MyObject)。一个类可以有多个实例。
Object serves the same(and some additional) purposesas the static methods and fields in Java.
对象与 Java 中的静态方法和字段具有相同(和一些额外)的用途。
回答by acjay
As has been explained by many, objectdefines a singleton instance. The one thing in the answers here that I believe is left out is that objectserves several purposes.
正如许多人所解释的,object定义了一个单例实例。我认为这里的答案中被遗漏的一件事是它有object多种用途。
It can be the companion object to a
class/trait, containing what might be considered static methods or convenience methods.It can act much like a module, containing related/subsidiary types and definitions, etc.
It can implement an interface by extending a
classor one or moretraits.It can represent a case of a
sealed traitthat contains no data. In this respect, it's often considered more correct than acase classwith no parameters. The special case of asealed traitwith onlycase objectimplementors is more or less the Scala version of an enum.It can act as evidence for
implicit-driven logic.It introduces a singleton type.
它可以是伴侣对象为
class/trait,包含了可能被认为是静态的方法或便捷方法。它可以像一个模块一样运行,包含相关/子类型和定义等。
它可以通过扩展一个
class或一个或多个traits来实现一个接口。它可以表示
sealed trait不包含数据的情况。在这方面,它通常被认为比case class没有参数的a 更正确。sealed trait只有case object实现者的 a 的特殊情况或多或少是枚举的 Scala 版本。它可以作为
implicit驱动逻辑的证据。它引入了单例类型。
It's a very powerful and general construct. What can be very confusing to Scala beginners is that the same construct can have vastly different uses. And an objectcan serve many of these different uses all at once, which can be even more confusing.
这是一个非常强大和通用的构造。Scala 初学者可能会感到非常困惑的是,相同的构造可能有截然不同的用途。并且 anobject可以同时用于许多这些不同的用途,这可能会更加混乱。
回答by Ken Bloom
Defining an object in Scala is like defining a class in Java that has only static methods. However, in Scala an object can extend another superclass, implement interfaces, and be passed around as though it were an instance of a class. (So it's like the static methods on a class but better).
在 Scala 中定义一个对象就像在 Java 中定义一个只有静态方法的类。然而,在 Scala 中,一个对象可以扩展另一个超类,实现接口,并像类的实例一样传递。(所以它就像类上的静态方法,但更好)。
回答by irudyak
The formal difference -
形式上的区别——
- you can not provide constructor parameters for Objects
- Objectis not a type - you may not create an instance with new operator. But it can have fields, methods, extend a superclass and mix in traits.
- 你不能为对象提供构造函数参数
- 对象不是类型 - 您不能使用 new 运算符创建实例。但它可以有字段、方法、扩展超类和混合特征。
The difference in usage:
用法上的区别:
- Scala doesn't have static methods or fields. Instead you should use
object. You can use it with or without related class. In 1st case it's called a companion object. You have to:- use the same name for both class and object
- put them in the same source file.
To create a program you should use main method in
object, not inclass.object Hello { def main(args: Array[String]) { println("Hello, World!") } }You also may use it as you use singleton object in java.
??
????
??
- Scala 没有静态方法或字段。相反,您应该使用
object. 您可以在有或没有相关类的情况下使用它。在第一种情况下,它被称为伴随对象。你必须:- 对类和对象使用相同的名称
- 将它们放在同一个源文件中。
要创建程序,您应该在 中使用 main 方法
object,而不是在 中class。object Hello { def main(args: Array[String]) { println("Hello, World!") } }您也可以像在 java 中使用单例对象一样使用它。
??
????
??
回答by irudyak
The objectkeyword creates a new singleton type, which is like a classthat only has a single named instance. If you're familiar with Java, declaring an objectin Scala is a lot like creating a new instance of an anonymous class.
该对象关键字创建一个新的单型,这就好比一个类是只有一个命名实例。如果您熟悉 Java,那么在 Scala 中声明一个对象很像创建一个匿名类的新实例。
Scala has no equivalent to Java's statickeyword, and an objectis often used in Scala where you might use a class with static members in Java.
Scala 没有与 Java 的static关键字等效的关键字,并且在 Scala 中经常使用对象,您可能会在 Java 中使用具有静态成员的类。
回答by Yonggoo Noh
Objectis a class but it already has(is) an instance, so you can not call new ObjectName. On the other hand, Classis just type and it can be an instance by calling new ClassName().
Object是一个类,但它已经(是)一个实例,所以你不能调用new ObjectName. 另一方面,Class只是类型,它可以通过调用new ClassName().
回答by Bhaskar Das
In scala, there is no staticconcept. So scala creates a singleton object to provide entry point for your program execution.
If you don't create singleton object, your code will compile successfully but will not produce any output. Methods declared inside Singleton Object are accessible globally. A singleton object can extend classes and traits.
在Scala中,没有static概念。所以 scala 创建了一个单例对象来为你的程序执行提供入口点。如果您不创建单例对象,您的代码将成功编译但不会产生任何输出。在单例对象中声明的方法可以全局访问。单例对象可以扩展类和特征。
Scala Singleton Object Example
Scala 单例对象示例
object Singleton{
def main(args:Array[String]){
SingletonObject.hello() // No need to create object.
}
}
object SingletonObject{
def hello(){
println("Hello, This is Singleton Object")
}
}
Output:
输出:
Hello, This is Singleton Object
In scala, when you have a class with same name as singleton object, it is called companion class and the singleton object is called companion object.
在scala中,当你有一个与单例对象同名的类时,它被称为伴生类,而单例对象被称为伴生对象。
The companion class and its companion object both must be defined in the same source file.
伴生类及其伴生对象都必须在同一个源文件中定义。
Scala Companion Object Example
Scala 伴随对象示例
class ComapanionClass{
def hello(){
println("Hello, this is Companion Class.")
}
}
object CompanoinObject{
def main(args:Array[String]){
new ComapanionClass().hello()
println("And this is Companion Object.")
}
}
Output:
输出:
Hello, this is Companion Class.
And this is Companion Object.
In scala, a class can contain:
在 Scala 中,一个类可以包含:
1. Data member
1. 数据成员
2. Member method
2.会员方式
3. Constructor Block
3. 构造块
4. Nested class
4. 嵌套类
5. Super class information etc.
5.超级班信息等。
You must initialize all instance variables in the class. There is no default scope. If you don't specify access scope, it is public. There must be an object in which main method is defined. It provides starting point for your program. Here, we have created an example of class.
您必须初始化类中的所有实例变量。没有默认范围。如果您不指定访问范围,则它是公开的。必须有一个定义了 main 方法的对象。它为您的程序提供了起点。在这里,我们创建了一个类的例子。
Scala Sample Example of Class
Scala 类的示例示例
class Student{
var id:Int = 0; // All fields must be initialized
var name:String = null;
}
object MainObject{
def main(args:Array[String]){
var s = new Student() // Creating an object
println(s.id+" "+s.name);
}
}
I am sorry, I am too late but I hope it will help you.
对不起,我来晚了,但我希望它会帮助你。
回答by FOD
Scala class same as Java Class but scala not gives you any entry method in class, like main method in java. The main method associated with object keyword. You can think of the object keyword as creating a singleton object of a class that is defined implicitly.
Scala 类与 Java 类相同,但 Scala 没有为您提供类中的任何入口方法,如 java 中的 main 方法。与 object 关键字关联的主要方法。您可以将 object 关键字视为创建隐式定义的类的单例对象。
more information check this article class and object keyword in scala programming
更多信息请查看本文 在Scala编程中的类和对象关键字

