Kotlin is easy – Class vs object: Object expression and Object declaration

Tram Ho

When to use

  • When you want to create an object with small changes of the class without having to explicitly declare the subclass of that class.

Object expression

  • Creates an object of an anonymous class that inherits from one or more other types. Such an object is called an anonymous object (the side name is anonymous object), the syntax:

    If the parent type has a constructor, the appropriate parameters must be passed to that constructor. If there are multiple types father inherited / deployment, they are separated by a semicolon separated , :

    If only objects are needed, not parent type:
  • Anonymous object can be used as a type only if local and private declarations.
  • If an anonymous object is used as the return type of the public or the declared type of public properties, the actual type of that method / property will be specified as the type of the parent of the anonymous object or is Any if no parent type has been declared before. And the component added in the anonymous object will be inaccessible:
  • The code in an object expression can access variables from a range that surrounds the object expression :

Object declaration

  • Singleton partern can be useful in many cases, declaring singleton in Kotlin is very easy like this:

    The declaration DataProviderManager as above is the declaration object , and it always has a defined name after the object keyword.
  • Like declaring a variable, a object declaration is not an expression, and cannot be used on the right side of an assignment.
  • To refer to the object, use its name directly: DataProviderManager.registerDataProvider(...)
  • These objects can have parent type
  • Object daclaration cannot be local (eg in a method), but it can be declared in another daclaration object or a non-inner class.

Companion object

  • The declaration object inside a class can be marked with the companion keyword:
  • Companion object components can be called by separating the class name: val instance = MyClass.create()
  • There is a tag that does not need to declare the name of companion object , in this case the name Companion will be used:
  • Although companion object components seem like static components in other languages, at runtime they are still and instances of an actual object and can do a number of things, such as implementing interfaces:
  • However, companion object components can be created as static methods and static fields if using JvmStatic annotation.

Difference

  • Some important differences between object expression and declaration object :
  1. Object expression is executed and instantiated as soon as it is used.
  2. The Object declaration is initialized late when the object is first accessed.
  3. Companion object is instantiated when the corresponding class is uploaded,
Share the news now

Source : Viblo