简体   繁体   English

Scala类方法

[英]Scala Class Methods

I'm new to programming and Scala. 我是编程和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. 我所能理解的是,正在使用Class(Number)作为参数创建方法(添加)。 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)) ). 创建Number的实例( (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 . 它可以立即使用,因此下一步是调用add()方法,该方法返回Number Then we get the member variable i from the Number instance 然后我们从Number实例获得成员变量i

First you need to understand few things here 首先,您需要了解一些事情

1) add is the method of the class Number . 1) addNumber类的方法。 So, add method can be invoked on the instance (object) of the Number class. 因此,可以在Number类的实例(对象)上调用add方法。

Thats what is happening here 那就是这里发生的事情

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

              ^

2) add method takes Number object as the input parameter. 2) add方法以Number对象为输入参数。 So, you can add Number instance to add method 因此,您可以添加Number实例来add方法

(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). 3) add方法方法返回Number类型,并且Number类包含i作为公共值(变量)。 So, you can do numberInstance.i to get the value of the Integer in the Number class 因此,您可以执行numberInstance.i以在Number类中获取Integer的值。

thats what is happening here 多数民众赞成在这里发生了什么

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

                                  ^

So, finally 所以,最后

23 - 1 is the result. 23 - 1是结果。

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). 添加方法采用i在其上调用的实例的值,并把它添加到i被给予作为输入参数,将其与从结果创建一个Number实例实例的值(与包装Number类的数量)。 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). 还可以省略返回类型,因为编译器可以弄清楚返回类型应该是什么(在这种情况下为Number )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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