简体   繁体   中英

Clarification on `this` keyword in Scala

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


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) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM