Programing

Scala에서 객체와 클래스의 차이점

lottogame 2020. 10. 3. 09:48
반응형

Scala에서 객체와 클래스의 차이점


인터넷에서 몇 가지 Scala 자습서를 살펴보고 일부 예제에서 예제 시작 부분에 개체가 선언되어 있음을 확인했습니다.

의 차이 무엇입니까 classobject스칼라는?


tl; dr

  • class C Java 또는 C ++에서와 마찬가지로 클래스를 정의합니다.
  • object O익명 클래스의 인스턴스로 싱글 톤 객체 O생성합니다 . 일부 클래스의 인스턴스와 연결되지 않은 정적 멤버를 보유하는 데 사용할 수 있습니다.
  • object O extends T객체를 O의 인스턴스로 만듭니다 trait T. 그런 다음 O어디든 통과 할 수 있습니다 T.
  • 가있는 경우 class C, 다음 object C은 IS 동반자 객체 클래스는 C; 컴패니언 객체는 자동으로의 인스턴스 아닙니다C .

객체클래스에 대한 Scala 문서도 참조하십시오 .

정적 멤버의 호스트로 사용

대부분의 경우 object일부 클래스의 인스턴스를 먼저 인스턴스화하지 않고도 사용할 수있는 메서드와 값 / 변수를 보유해야합니다. 이것은 staticJava의 멤버 와 밀접한 관련이 있습니다 .

object A {
  def twice(i: Int): Int = 2*i
}

그런 다음을 사용하여 위의 메서드를 호출 할 수 있습니다 A.twice(2).

경우 twice일부 클래스의 멤버였다 A, 당신은 첫 번째 인스턴스를 만들 필요가있다 :

class A() {
  def twice(i: Int): Int = 2 * i
}

val a = new A()
a.twice(2)

twice인스턴스 별 데이터가 필요하지 않으므로 이것이 어떻게 중복되는지 확인할 수 있습니다 .

특별한 명명 된 인스턴스로 사용

object그 자체를 클래스 나 특성의 특별한 인스턴스로 사용할 수도 있습니다 . 이 작업을 수행 할 때 객체 trait는 하위 클래스의 인스턴스가되기 위해 일부를 확장해야 합니다.

다음 코드를 고려하십시오.

object A extends B with C {
  ...
}

이 선언은 먼저 B모두를 확장하는 익명 (액세스 할 수없는) 클래스를 선언하고 C라는이 클래스의 단일 인스턴스를 인스턴스화합니다 A.

이는 또는 , 또는 A유형의 객체를 예상하는 함수에 전달할 수 있음을 의미 합니다.BCB with C

추가 기능 object

Scala에는 객체의 몇 가지 특별한 기능도 있습니다. 공식 문서 를 읽는 것이 좋습니다 .

  • def apply(...) 일반적인 메서드 이름없는 구문을 활성화합니다. A(...)
  • def unapply(...)사용자 지정 패턴 일치 추출기 를 만들 수 있습니다.
  • 동일한 이름의 클래스가 동반되는 경우 객체는 암시 적 매개 변수를 확인할 때 특별한 역할을 맡습니다.

A class는 정의, 설명입니다. 다른 유형의 방법 및 구성 측면에서 유형을 정의합니다.

An object은 싱글 톤 (고유함이 보장되는 클래스의 인스턴스)입니다. 모든 object코드에 대해 object구현하도록 선언 한 모든 클래스에서 상속되는 익명 클래스가 생성 됩니다. 이 클래스는 Scala 소스 코드에서 볼 수 없지만 리플렉션을 통해 얻을 수 있습니다.

사이의 관계가있다 object하고 class. 동일한 이름을 공유하는 객체는 클래스의 동반 객체라고합니다. 이런 일이 발생하면 각각은 private다른 사람 가시성 방법에 액세스 할 수 있습니다 . 그러나 이러한 메서드는 자동으로 가져 오지 않습니다. 명시 적으로 가져 오거나 클래스 / 객체 이름을 접두사로 지정해야합니다.

예를 들면 :

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
   }
}

객체에는 정확히 하나의 인스턴스가 있습니다 (를 호출 할 수 없음 new MyObject). 클래스의 여러 인스턴스를 가질 수 있습니다 .

객체는 Java의 정적 메소드 및 필드 동일한 (및 일부 추가) 목적 을 제공합니다.


As has been explained by many, object defines a singleton instance. The one thing in the answers here that I believe is left out is that object serves several purposes.

  • 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 class or one or more traits.

  • It can represent a case of a sealed trait that contains no data. In this respect, it's often considered more correct than a case class with no parameters. The special case of a sealed trait with only case object implementors is more or less the Scala version of an enum.

  • It can act as evidence for implicit-driven logic.

  • It introduces a singleton type.

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 object can serve many of these different uses all at once, which can be even more confusing.


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).


The formal difference -

  1. you can not provide constructor parameters for Objects
  2. Object is 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.

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:
    1. use the same name for both class and object
    2. put them in the same source file.
  • To create a program you should use main method in object, not in class.

    object Hello {
      def main(args: Array[String]) {
        println("Hello, World!")
      }
    }
    
  • You also may use it as you use singleton object in java.

      
        
      


The object keyword creates a new singleton type, which is like a class that only has a single named instance. If you’re familiar with Java, declaring an object in Scala is a lot like creating a new instance of an anonymous class.

Scala has no equivalent to Java’s static keyword, and an object is often used in Scala where you might use a class with static members in Java.


Object is a class but it already has(is) an instance, so you can not call new ObjectName. On the other hand, Class is just type and it can be an instance by calling new ClassName().


In scala, there is no static concept. 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 Singleton Object Example

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.

The companion class and its companion object both must be defined in the same source file.

Scala Companion Object Example

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:

1. Data member

2. Member method

3. Constructor Block

4. Nested class

5. Super class information etc.

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.

Scala Sample Example of Class

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.


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.

more information check this article class and object keyword in scala programming


The object equals to the static class in Java to some extends, the static characteristics mean the static class need't to creat an object when putting to the JVM,it can be used by it's class name directly


If you are coming from java background the concept of class in scala is kind of similar to Java, but class in scala cant contain static members.

Objects in scala are singleton type you call methods inside it using object name, in scala object is a keyword and in java object is a instance of class


A class is just like any other class in other languages. You define class just like any other language with some syntax difference.

class Person(val name: String)
val me = new Person("My name")

However, object is a class with single object only. This makes it interesting as it can be used to create static members of a class using companion object. This companion object has access to private members of the class definition and it has the same name as the class you're defining.

class Person(var name: String) {

  import Person._

  def hi(): String = sayHello(name)
}

object Person {
  private def sayHello(name: String): String = "Hello " + name
}

val me = new Person("My name")
me.hi()

Also, noteworthy point is that object class is lazily created which is another important point. So, these are not instantiated unless they are needed in our code.

If you're defining connection creation for JDBC, you can create them inside object to avoid duplication just like we do in Java with singleton objects.


Class & object: a class is a definition which describes all attributes of entity or an object. And object is an instance of a class.

참고URL : https://stackoverflow.com/questions/1755345/difference-between-object-and-class-in-scala

반응형