Scala Class Variable Name Hides Method Parameter Name
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 co开发者_如何学Curse, 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 var
when you return a new object in chngName
?)
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:
def chngName(name:String) = {
val _name = name
new Person() { name = _name }
}
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 the var
suffices.
If you want to return a completely new object, you may consider using a case class
which adds a copy
method with the same semantics and identically named method arguments. (So you can use named arguments):
case class Person(name: String)
val p = Person("bob")
p.name // bob
val q= p.copy(name = "aa")
q.name // aa
q == p // false
The block you passed after new Person()
lies in the Person
initialization body (it's inside the constructor if you prefer). In this scope name
is defined as the class field. (so name
is the same as this.name
).
this works as intended (although is much less concise)
def chngName(name:String) = {val r = new Person; r.name=name; r;}
精彩评论