Reputation: 439
I'm new to scala, and is trying to follow the tutorial on the documentation. I understand that this
is used to 'access' a class' methods or fields, but on this code block, this is called as without any 'option' but it default to call the 'toString' method.
Here's the code block i'm talking about
class Person(var firstName: String, var lastName: String) {
println("the constructor begins")
// 'public' access by default
var age = 0
// some class fields
private val HOME = System.getProperty("user.home")
// some methods
override def toString(): String = s"$firstName $lastName is $age years old"
def printHome(): Unit = println(s"HOME = $HOME")
def printFullName(): Unit = println(this)
printHome()
printFullName()
println("you've reached the end of the constructor")
}
Output in REPLL:
scala> val p = new Person("Kim", "Carnes")
the constructor begins
HOME = /Users/al
Kim Carnes is 0 years old
you've reached the end of the constructor
p: Person = Kim Carnes is 0 years old
Upvotes: 1
Views: 1857
Reputation: 439
Thanks to Luis. His answer:
println calls the toString method of whatever is passed to it. So the object itself was passed to the println function which then called toString to it. Does that makes sense?
Basically, println(this)
has the same output when you call println(p)
.
Upvotes: 2