steve steve - 1 month ago 8
Scala Question

get confuse when call primary constructor in scala

I am learning the scala and I have try with the following code.

object Demo7 {
def main(args: Array[String]): Unit = {
class Person(val fullName: String) {
println(s"This is the primary constructor. Name is ${fullName}")
val initial = fullName.substring(0, 1) // Computed during initialization

//def this(firstName: String, lastName: String) = this(s"$firstName $lastName")

}
new Person("Tek Tuk")
new Person("Tek Tuk").fullName

}
}


then I run I get the same returned result as each call.
for my understanding this line

new Person("Tek Tuk").fullName


Shouldn't compile, anyone can explain me why this line get compile and return the same result as the first line?

Thank you.

Answer

If you're asking why you're allowed to access the fullName field of your Person class, that's because you've declared it as a val in the parameter list.

This is the same as declaring it a public final field in Java. If you want it to be private, just remove the val part, i.e.

class Person(fullName: String) {
  (...)
}

As for why both calls "return" the same thing - they don't.

  • new Person("Tek Tuk")" returns an instance of Person.
  • new Person("Tek Tuk")" returns "Tek Tuk" - a String. You created another instance of Person with the same firstName and you called firstName on it.

Both, however, print "This is the primary constructor. Name is Tek Tuk", because you called the same constructor in both cases and you have a println that prints this in the constructor.