In Scala, there's many way to create object:
For example, creating through class with new keyword
class Car {
def startEngine() = println("run....")
}
val car = new Car
car.startEngine() // run....
where car object should act like "newed" object in Java seating in heap and waiting to be garbage collected as it is de-referenced.
So, how about creating though trait?
trait Car {
def startEngine() = println("run...")
}
val car = new Car {}
car.startEngine() //run....
This is a valid syntax that creating object with using class myCar extends Car. Instead, it just creating object from Trait.
Does it object seats in heap? (I guess it is not) So, does it live in stack and will be de-referenced as local variable once out of scoop?
At last, how about via Object?
object Car {
def startEngine() = println("run...")
}
Car.startEngine() //run....
Is this the same case as via Trait? I believe object is more likely living in the stack.
Could someone please shed some light about the difference among this 3 syntax, in terms of memory allocation?
They all live in the heap. (Also, your second example didn't work as written.)
The difference is in code reuse.
With a class, each new object of that class runs the same code:
class Car { }
val c1 = new Car
val c2 = new Car // Same code as c1
c1.getClass == c2.getClass // true
c1 eq c2 // false--different objects on the heap
With a trait, each time you make a class from it, it copies the code (at least a forwarder). So it's less efficient but more flexible (because you can mix it into other classes when you need it). And you can make a new anonymous class for each object just by adding {}, so it's easy to do a lot of work for nothing:
trait Car { }
val t1 = new Car {} // Anon class #1
val t2 = new Car {} // Anon class #2--duplicate of #1
t1.getClass == t2.getClass // false
With an object, you explicitly say there's going to be only one. You can't (without low-level trickery) get another.
object Car { }
val o1 = Car
val o2 = Car
o1 eq o2 // true -- there is only one Car
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With