41.scala编程思想笔记——伴随对象
欢迎转载,转载请标明出处:http://blog.youkuaiyun.com/notbaron/article/details/50447586
源码下载连接请见第一篇笔记。
方法作用于类的特定对象:
例如:
import com.atomicscala.AtomicTest._
class X(val n:Int) {
def f = n *10
}
val x1 = new X(1)
val x2 = new X(2)
x1.f is 10
x2.f is 20
scala跟踪感兴趣的对象的方式是默默地传递一个指向该对象的引用,这个引用可以用关键字this获取。可以显示地访问this,例如:
import com.atomicscala.AtomicTest._
class X(val n:Int) {
def f =this.n * 10
}
val x1 = new X(1)
val x2 = new X(2)
x1.f is 10
x2.f is 20
scala的object关键字定义了看起来大体上与类相同的事务,只是不能创建object的任何实例。
例如:
import com.atomicscala.AtomicTest._
object X {
val n = 2
def f = n *10
def g =this.n * 20
}
X.n is 2
X.f is 20
X.g is 40
Object关键字允许创建类的伴随对象。普通对象和伴随对象的唯一差异就是后者的名字与常规类的名字相同。
如果在伴随对象的内部创建一个域,那么不论创建多少个关联类的实例,都只会为该域产生单一的数据存储。
例如:
import com.atomicscala.AtomicTest._
class X {
defincrement() = { X.n += 1; X.n }
}
object X {
var n:Int = 0// Only one of these
}
var a = new X
var b = new X
a.increment() is 1
b.increment() is 2
a.increment() is 3
当一个方法只访问伴随对象的域时,将该方法移动到伴随对象中就变得很有意义了,如下:
import com.atomicscala.AtomicTest._
class X
object X {
var n:Int = 0
defincrement() = { n += 1; n }
def count() =increment()
}
X.increment() is 1
X.increment() is 2
X.count() is 3
伴随对象并非严格必需的,但是他们使代码组织得到了优化,并且使代码更加易于理解。