I wonder why I can’t use the same name for function parameter and the name used in a class. Please refer to the following example.
scala> class Person() {var name = "bob" }
defined class Person
scala> val p = new Person
p: Person = Person@486f8860
scala> p.name
res0: java.lang.String = bob
scala> p.name = "alice"
scala> p.name
res1: java.lang.String = alice
scala> def chngName(name:String) = new Person() {this.name= name}
chngName: (name: String)Person
scala> val p = chngName("aa")
p: Person = $anon$1@3fa1732d
scala> p.name
res2: java.lang.String = bob
scala> def chngName(n:String) = new Person() {name= n}
chngName: (n: String)Person
scala> val p = chngName("aa")
p: Person = $anon$1@19d2052b
scala> p.name
res3: java.lang.String = aa
Of course, I can use a different name but I want to why I can’t or there is something I am miss here. Thanks
(Why do want to use
varwhen you return a new object inchngName?)As has been said, the class’s field of the same name shadows the method argument.
You could of course rename it before entering the class’s scope:
For this use case, there are a few other options, however. It depends, though, whether you want to copy the object, ie. return a
new Person, or if a simple change of thevarsuffices.If you want to return a completely new object, you may consider using a
case classwhich adds acopymethod with the same semantics and identically named method arguments. (So you can use named arguments):