scala 第一天

来源:互联网 发布:16年广东省的经济数据 编辑:程序博客网 时间:2024/06/02 02:04
/**  */// 匿名函数val addOne = (x:Int)=>x+1val getTheAnswer = ()=>3// 相当于new Function1[Int, Int] {// 第一个是入参,第二个是出参  def apply(x: Int): Int = x + 1}// 方法// 方法和函数不同,区别如下//方法以def开头,后面是名称,参数列表和返回类型//参数列表可以没有,也可以有多个//类// 关键字 class 类名 成员列表 (是写在紧接后的括号里)// 可以用 new实例化// 类包括 : 方法 值 变量 类型 对象 trait 成员// 成员包括:成员变量 成员方法// 默认的构造函数就是类的签名 ,所以成员变量也可以有默认的值// 成员默认是公共的{  class Point(var x: Int, var y : Int= 0) {    def move(dx: Int, dy: Int): Unit = {      x = x + dx      y = y + dy    }    // 任何类都有toString函数,所以需要重写的时候要写成override    //    默认会写$line18.$read$$iw$$iw$Point@ef09e1    override def toString: String =      s"($x, $y)"//  TODO s 是什么  }  val point1 = new Point(2, 3)  point1.x // 2  println(point1)}// 私有的成员变量{  class Point2 {    private var _x = 0    private var _y = 0    private val bound = 100    def xx = _x // getter 函数    // setter函数 名字要和getter函数对应    def xx_=(newValue: Int): Unit = {      if (newValue < bound) _x = newValue else printWarning    }    def yy = _y    def yy_=(newValue: Int): Unit = {      if (newValue < bound) _y = newValue else printWarning    }    private def printWarning = println("WARNING: Out of bounds")  }  val point21 = new Point2  point21.xx = 99  point21.yy = 101 // prints the warning}{  class Point(val x: Int, val y: Int)// 常亮 不可变  val point = new Point(1, 2)  point.x = 3 // <-- does not compile}{  class Point(x: Int, y: Int) // 默认私有 不可接触  val point = new Point(1, 2)  point.x // <-- does not compile}//TODO 如何和Point2结合
0 0
原创粉丝点击