Reputation: 67
I am having my first experience with Scala, experimenting with basic concepts. I made a very simple class, doing shenanigans with overriding toString
for printing the class instance upon creation:
class Person(var firstName: String, var lastName: String) {
println(this)
override def toString: String = "Overriden toString"
println(this)
}
val p = new Person("John", "Smith")
I wondered what would happen if I run this code. First println
before overriding toString
is supposed to be
PlatformName$Person@address
if I understand it correctly, which is what you supposed to get when printing a class instance without overriding toString
. But instead, both prints on construction printed
Overriden toString.
Why it is so? Does override
takes the first priority over any other code, ignoring the order, or how does it work?
Upvotes: 2
Views: 215
Reputation: 15080
When you're defining such a class, you're basically writing the same thing as:
class Person {
var firstName: String
var lastName: String
// Constructor
def this(firstName: String, lastName: String) = {
// Regular constructor member definition
this.firstName = firstName
this.lastName = lastName
// The code you wrote in the class body
println(this)
println(this)
}
override def toString: String = "Overriden toString"
}
The code written in the class that is not part of a def
will be executed when an instance of the class is created (in the constructor at run-time).
The def
of the class are all defined (at compile-time) before you instantiate a class, no matter the order or the override
.
Upvotes: 4
Reputation: 3173
There are 2 points of view (from my opinion):
1st is that toString method is evaluated in compile time, but println is when object is created and is done at runtime.
2nd is that when you want to print something, you are implicitly calling .toString()
method (not only in Scala, same in Java and ...), so the method needs to be evaluated first, and when you call it (implicitly) you happen to see overriden string whenever you println that object.
Upvotes: 1