Scala: How to change some variable in a class by method?

Possible duplicate:
Using def, val and var in scala

I am studying Scala right now and I cannot change a variable in a class.

class Person(name: String, var variable: Int) { def change() { variable = 42 } } def person = new Person("name", 0) println(person.variable) person.change() println(person.variable) 

And the result:

 0 0 

Why does the output contain 2 times 0?

How can I change a variable in this code?

I have Scala version 2.9.1.

+4
source share
3 answers

It took me a while too :)

You do not define the person val or var ", but create a new person method. Therefore, every time you call person , it creates a new instance of person , which will always have its variable for 0 This is a side effect of the fact that in Scala you no need to () call invisible methods.

 def person = new Person("foo", 1) 

roughly equivalent (in java code)

 public Person person() { return new Person("foo", 1); } 

whereas val person is what you want, i.e.

 Person person = new Person("foo", 1) 

(of course, this is not a real val , because Scala does not support these :))

and when you use person , what Scala understands is person() .

Just change def , which is used to define methods, to val or var , and everything will be fine :)

+11
source

It was not easy to notice! Here:

 def person = new Person("name", 0) 

you define a method called person . To make this clearer, you are doing something like this:

 def person(): Person = { return new Person("name", 0) } 

This means that every time you say person , you do not mean a variable, but you call a method and create a new instance again and again.

Just say val person = ... and everything will be alright.

Believe it or not, this is actually a feature of the language. For instance. you can create a field ( val ) in your class and then change your mind and turn it into a getter by simply changing to def . From the point of view of client code, nothing changes.

+5
source

Analyze your code in parts. First you declared a class called a person. class Person(name: String, var variable: Int) with two parameters, a name and a variable. In this class, you have a method: def change() .

and it has a variable with 42 as its value. Then you called the def change() method on person.change()

This person.change() does not actually change the value of var variable , but actually calls the method itself. Try making println(person.change()) and you will see that it prints "42".

I think you still do not understand the difference between class and def. if you want to change the value of the class Person , a new def is required to invoke the change.

  class Person(name: String, var variable: Int) { println(variable) } def changePerson = Person("new value of name here", "new value of variable here"); 

Now call defChangePerson and it will now print the value you passed to it.

0
source

Source: https://habr.com/ru/post/1443528/


All Articles