注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

阿弥陀佛

街树飘影未见尘 潭月潜水了无声 般若观照心空静...

 
 
 

日志

 
 
关于我

一直从事气象预报、服务建模实践应用。 注重气象物理场、实况场、地理信息、本体知识库、分布式气象内容管理系统建立。 对Barnes客观分析, 小波,计算神经网络、信任传播、贝叶斯推理、专家系统、网络本体语言有一定体会。 一直使用Java、Delphi、Prolog、SQL编程。

网易考拉推荐

scala companion object  

2013-08-04 09:04:23|  分类: Scala |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |
package points
class Point(
    // adding `val` here automatically creates
    // public accessor methods named `x` and `y`
    val x: Double, val y: Double,
    addToGrid: Boolean = false
) {
  // import functions/vars from companion object
  import Point._
  if (addToGrid) grid.add(x,y)
  def this() {
    this(0.0, 0.0)
  }
 
  def distanceToPoint(other: Point) =   distanceBetweenPoints(x, y, other.x, other.y)
}
 
object Point {
  // private/protected members shared between
  // class and companion object
  private val grid = new Grid()
 
  def distanceBetweenPoints(x1: Double, y1: Double,  x2: Double, y2: Double) = {
    val xDist = x1 - x2
    val yDist = y1 - y2
    math.sqrt(xDist*xDist + yDist*yDist)
  }
  def main(args: Array[String]) {
    grid.add(1,2)
    val l = grid.add(3,4)
    println(l)
  }
}

class Grid{
  var points = List[(Double,Double)]()
  def add(x:Double,y:Double)={
    points = (x,y)::points
    points
  }
}
运行结果:
List((3.0,4.0), (1.0,2.0))
============================================================================
Scala has no static variables or methods. Instead, it has singleton objects, which are essentially classes with only one object in the class. Singleton objects are declared using object instead of class. It is common to place static variables and methods in a singleton object with the same name as the class name, which is then known as a companion object. (The underlying class for the singleton object has a $ appended. Hence, for class Foo with companion object object Foo, under the hood there's a class Foo$ containing the companion object's code, and a single object of this class is created, using the singleton pattern.)
  评论这张
 
阅读(774)| 评论(0)
推荐 转载

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017