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
https://stackoverflow.com/questions/65768252/clarification-on-this-keyword-in-scala January 18, 2021 at 10:56AM
没有评论:
发表评论