0

What is different between Factory and Factory2? They both seem to do same thing.

data class Car(val horsepowers: Int) {
companion object Factory {
    val cars = mutableListOf<Car>()

    fun makeCar(horsepowers: Int): Car {
        val car = Car(horsepowers)
        cars.add(car)
        return car
    }
}
object Factory2 {
    val cars = mutableListOf<Car>()
    fun makeCar(horsepowers: Int): Car {
        val car = Car(horsepowers)
        cars.add(car)
        return car
    }
}
}
noob
  • 774
  • 1
  • 10
  • 23
Thaer
  • 61
  • 3
  • 2
    Possible duplicate of [Kotlin: Difference between object and companion object in a class](https://stackoverflow.com/questions/43814616/kotlin-difference-between-object-and-companion-object-in-a-class) – Vishnu Haridas Feb 06 '19 at 10:00
  • But it doesn't answer what is advantage of the companion object over the object? – Thaer Feb 07 '19 at 08:12

3 Answers3

2

A companion object is a specific type of object declaration that allows an object to act similar to static objects in other languages (such as Java). Adding companion to the object declaration allows for adding the "static" functionality to an object even though the actual static concept does not exist in Kotlin.

1

Object in kotlin is a way of implementing Singletons.

object MyObject {

// further implementation
  
  fun printHello() {
    println("Hello World!")
  }
  
}

This implementation is also called object declaration. Object declarations are thread-safe and are lazy initialized, i.e. objects are initialized when they are accessed for the first time.

Companion Object If we want some implementation to be a class but still want to expose some behavior as static behavior, companion object come to the play. These are object declarations inside a class. These companion objects are initialized when the containing class is resolved, similar to static methods and variables in java world.

class MyClass {

  // some implementations
  
  companion object {
    val SOME_STATIC_VARIABLE = "STATIC_VARIABLE"
    fun someStaticFunction() {
      // static function implementation
    }
  }
}
Asad Mukhtar
  • 391
  • 6
  • 18
0

Properties and functions declared in a companion object can be access directly by using the class name, same as we access static members in java.

so in your code, makeCar function of Factory can be called in two following ways

Car.makeCar(50)         // From outside the class
Car.Factory.makeCar(50) // From outside the class
makeCar(50)             // From inside the class
Factory.makeCar(50)     // From insie the class

on the other hand makeCar function of Factory2 can only be called as follows.

Car.Factory2.makeCar(50) // From outside the class
Factory2.makeCar(50)     // Inside the class
mightyWOZ
  • 7,946
  • 3
  • 29
  • 46