Reputation: 81
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
}
}
}
Upvotes: 1
Views: 2593
Reputation: 461
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
}
}
}
Upvotes: 1
Reputation: 8355
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
Upvotes: 0
Reputation: 543
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.
Upvotes: 2