code

Kotlin : 클래스에서 객체와 컴패니언 객체의 차이점

codestyles 2020. 12. 5. 09:47
반응형

Kotlin : 클래스에서 객체와 컴패니언 객체의 차이점


Kotlin의 클래스에서 객체와 컴패니언 객체의 차이점은 무엇입니까?

예:

class MyClass {

    object Holder {
        //something
    }

    companion object {
        //something
    }
}

포함 매개 변수 / 메소드가 해당 클래스와 밀접한 관련이있는 경우 컴패니언 객체가 사용된다는 것을 이미 읽었습니다.

하지만 클래스에서 일반 객체를 선언 할 가능성도있는 이유는 무엇입니까? 동반자와 똑같이 작동하지만 이름이 있어야하기 때문입니다.

"정적"(나는 자바 측 출신) 라이프 사이클에 차이가있을 수 있습니까?


객체는 인터페이스를 구현할 수 있습니다. 클래스 내에서 인터페이스를 구현하지 않는 간단한 객체를 정의하는 것은 대부분의 경우 이점이 없습니다. 그러나 다양한 인터페이스 (예 :)를 구현하는 여러 객체를 정의하는 Comparator것은 매우 유용 할 수 있습니다.

수명주기 측면에서 컴패니언 객체와 클래스에서 선언 된 명명 된 객체간에 차이가 없습니다.


두 가지 다른 유형의 object사용, 표현선언이 있습니다.

개체 표현

객체 표현식은 클래스에 약간의 수정이 필요할 때 사용할 수 있지만 완전히 새로운 하위 클래스를 만들 필요는 없습니다. 익명의 내부 클래스가 이에 대한 좋은 예입니다.

    button.setOnClickListener(object: View.OnClickListener() {
        override fun onClick(view: View) {
            // click event
        }
    })

주의해야 할 한 가지는 익명 내부 클래스가 둘러싸는 범위의 변수에 액세스 할 수 있으며 이러한 변수는 final. 이는 고려되지 않은 익명 내부 클래스 내에서 사용되는 변수 final가 액세스되기 전에 예기치 않게 값을 변경할 수 있음을 의미합니다 .

개체 선언

개체 선언은 변수 선언과 유사하므로 할당 문의 오른쪽에서 사용할 수 없습니다. 객체 선언은 Singleton 패턴을 구현하는 데 매우 유용합니다.

    object MySingletonObject {
        fun getInstance(): MySingletonObject {
            // return single instance of object
        }
    }

그런 다음 getInstance메서드를 이와 같이 호출 할 수 있습니다.

    MySingletonObject.getInstance()

동반자 개체

동반 객체는 객체가 다른 언어 (예 : Java)의 정적 객체와 유사하게 작동 할 수 있도록하는 특정 유형의 객체 선언입니다. 추가 companion객체 선언은 실제 정적 개념이 코 틀린에 존재하지 않는 경우에도 개체에 "정적"기능을 추가 할 수 있습니다. 다음은 인스턴스 메서드와 동반 메서드가있는 클래스의 예입니다.

 class MyClass {
        companion object MyCompanionObject {
            fun actsAsStatic() {
                // do stuff
            }
        }

       fun instanceMethod() {
            // do stuff
        }
    }

인스턴스 메소드를 호출하는 것은 다음과 같습니다.

    var myClass = MyClass()
    myClass.instanceMethod()

컴패니언 객체 메서드를 호출하는 것은 다음과 같습니다.

    MyClass.actsAsStatic()

See the Kotlin docs for more info.


An object, or an object declaration, is initialized lazily, when accessed for the first time.

A companion object is initialized when the corresponding class is loaded. It brings about the 'static' essence, although Kotlin does not inherently support static members.


Companion object exists because you can call companion objects' functions/properties like it is a java static method/field. And for why your Holder is allowed, well, there is no reason that declaring a nested object is illegal. It may comes in handy sometimes.


A Companion object is initialized when the class is loaded (typically the first time it's referenced by other code that is being executed) whereas Object declarations are initialized lazily, when accessed for the first time.

Please refer https://kotlinlang.org/docs/reference/object-declarations.html bottom section clearly defines the difference between these two.

참고URL : https://stackoverflow.com/questions/43814616/kotlin-difference-between-object-and-companion-object-in-a-class

반응형