티스토리 뷰

IT/Android

[Kotlin] object VS classs

ttoogi 2023. 5. 10. 18:36

object VS class

https://kotlinlang.org/docs/object-declarations.html#object-declarations-overview

class

  • 인스턴스를 변수에 대입하여 사용하는 방식이다.

object

  • expressions: 한번 사용하기 좋으며 익명 클래스라고도 한다.
  • declarations: 싱글톤 패턴에 유용하게 사용가능하다.

Object expressions

Object expressions create objects of anonymous classes, that is, classes that aren't explicitly declared with the class declaration. Such classes are useful for one-time use. You can define them from scratch, inherit from existing classes, or implement interfaces. Instances of anonymous classes are also called anonymous objects because they are defined by an expression, not a name.

Creating anonymous objects from scratch

Object expressions start with the object keyword.

If you just need an object that doesn't have any nontrivial supertypes, write its members in curly braces after object:

val helloWorld = object {
    val hello = "Hello"
    val world = "World"
    // object expressions extend Any, so override is required on toString()
    override fun toString() = "$hello $world"
}

Object declarations

The Singleton pattern can be useful in several cases, and Kotlin makes it easy to declare singletons:

This is called an object declaration, and it always has a name following the object keyword. Just like a variable declaration, an object declaration is not an expression, and it cannot be used on the right-hand side of an assignment statement.

The initialization of an object declaration is thread-safe and done on first access.

객체 표현식과 선언 간의 의미적 차이

객체 표현식과 객체 선언 사이에는 한 가지 중요한 의미론적 차이가 있습니다.

  • 객체 표현식(Object expressions)은 사용되는 즉시 실행(및 초기화)됩니다 .
  • 객체 선언(Object declarations)은 처음 액세스할 때 느리게 초기화됩니다 .
  • 동반 객체(A companion object)는 Java 정적 초기화 프로그램의 의미 체계와 일치하는 해당 클래스가 로드(해결)될 때 초기화됩니다.

Reference

https://medium.com/depayse/kotlin-%ED%81%B4%EB%9E%98%EC%8A%A4-10-object-%ED%82%A4%EC%9B%8C%EB%93%9C%EC%9D%98-%EC%82%AC%EC%9A%A9-d7fe736a3dcb


페이지에 한글과 영어 버전을 부분적으로 가져왔는데, 솔직히 expressions 와 declartaions 차이를 잘 모르겠다.