参考
《Scala 编程》
类、字段和方法
这三者的关系可以用下图来描述
字段,是指向对象(比如String对象)的变量,保留了该对象的状态或者数据
而方法,则使用字段保留的对象数据进行相应的运算工作
字段和方法,可以笼统的称之为类的成员(member)
类和对象
一旦有了类,就可以使用 new
来创建其对象
class TestClass {
var sum = 0;
}
val tc = new TestClass
Note: 与 java 不同的是,不用在后面加上括号 TestClass()
另外, val 对 tc 变量的局限仅在于不能将 tc 重新赋值到其他的类对象而已,其已有的是可以改变的
scala> tc = new TestClass
<console>:13: error: reassignment to val
tc = new TestClass
scala> tc.sum = 3
tc.sum: Int = 3
字段
当定义字段时加上 private
修饰符时,该字段只能在内部方法中访问,就算类的对象也得望尘莫及
scala> class TestClass { private var sum = 0; }
defined class TestClass
scala> val tc = new TestClass
tc: TestClass = TestClass@2ce80c85
scala> tc.sum
<console>:13: error: variable sum in class TestClass cannot be accessed in TestClass
tc.sum
^
方法
scala 方法的一个重要特征是其参数都是 val 类型,一旦传入,并不能改变其值
scala> def sum(a:Int, b:Int): Int = {a=3; a+b;}
<console>:11: error: reassignment to val
def sum(a:Int, b:Int): Int = {a=3; a+b;}
另外,从上面可以看到,方法并没有显示的 return
语句,其实,在 scala 中,其会自动将方法中最后一步的计算结果作为返回值
scala> def sum(a:Int, b:Int): Int = a+b
sum: (a: Int, b: Int)Int
scala> sum(1,2)
res3: Int = 3
也可以返回一个字符串
scala> def g() = "hello"
g: ()String
scala 会类型推断为返回 String 类型,如果不需要这个返回值的话,将结果类型定为 Unit
即可
还有一种情况是忘记写函数体之前的等号了,这样的话不管方法里面执行了什么,都将返回 Unit
scala> def f() {"hello"}
f: ()Unit