简体   繁体   中英

Scala Class Methods

I'm new to programming and Scala. I don't understand what's going on on second line of this code. All I can understand is A method(add) is being created with Class(Number) being the Argument. After that I draw blank. I would really appreciate if someone could interpret this code. Thanks

scala> class Number(val i:Int){
    def add(num: Number) = new Number(i + num.i)
}
scala> (new Number(23)).add(new Number(-1)).i
res18: Int = 22

An instance of Number is created ( (new Number(23)) ). It can be used right away, so the next thing is to call the add() method on it, which returns a Number . Then we get the member variable i from the Number instance

First you need to understand few things here

1) add is the method of the class Number . So, add method can be invoked on the instance (object) of the Number class.

Thats what is happening here

(new Number(23)).add(new Number(-1)).i

              ^

2) add method takes Number object as the input parameter. So, you can add Number instance to add method

(new Number(23)).add(new Number(-1)).i

                  ^

3) add method method returns Number type and Number class contains i as the public val (variable). So, you can do numberInstance.i to get the value of the Integer in the Number class

thats what is happening here

(new Number(23)).add(new Number(-1)).i

                                  ^

So, finally

23 - 1 is the result.

add method takes i value of the instance on which it is invoked and adds it to the i value of instance which is given as input parameter to it and creates a Number instance from the result (wraps the number with Number class). That is what is happening.

After the = is the body of the method. For methods that are only a single statement, curly braces are not needed. Return type can also be omitted because the compiler can figure out what the return type should be ( Number in this case).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM