天天看點

scala object類與普通class的差別與聯系

原讨論:http://stackoverflow.com/questions/1755345/scala-difference-between-object-and-class

class是定義是描述。它依照方法、或者其他組成元素定義一個類型。

object是單例。它是你所定義的類的唯一執行個體。每個代碼中的object都将建立一個匿名類,這個匿名類繼承了你聲明本object想要實作的類。

這個類在scala源代碼中不可見——是以,使用反射的方式來使用它!

class X {
  // 用法一:Prefix to call
  def m(x: Int) = X.f(x)

  // 用法二:Import and use
  import X._
  def n(x: Int) = f(x)
}

object X {
  def f(x: Int) = x * x
}