class Reference[T] {
  private var contents: T = _
  def set(value: T) { contents = value }
  def get: T = contents
}

类 Reference 带有一个类型参数 T,这个参数会是容器内元素的类型。此类型被用做 contents 变量的类型、 set 函数的对象类型、 get 函数的回传类型。

上面代码使用的 Scala 变量语法应该不需要过多的解释。值得注意的是赋与该变量的初始值是 _,该语法表示预设值。数值类型预设值是0,Boolean 类型是 false, Unit 类型是 () ,所有的对象类型是 null

为了使用 Reference 类型,我们必须指定 T,也就是这容器所包容的元素类型。举例来说,创造并使用该容器来容纳整数,我们可以这样写:

object IntegerReference {
  def main(args: Array[String]) {
    val cell = new Reference[Int]
    cell.set(13)
    println("Reference contains the half of " + (cell.get * 2))
  }
}