首页 > 代码库 > Scala:Functional Objects

Scala:Functional Objects

先上代码

 1 class FunctionalObjects(var _x: Int, var _y: Int) { 2   require(_x > 0) 3   require(_y > 0) 4  5   def this(value: Int) = this(value, value) 6  7   def x = _x 8  9   def x_=(value: Int) { _x = value }10 11   def y = _y12 13   def y_=(value: Int) { _y = value }14 15   def +(value: Int): FunctionalObjects = { 16     _x += value17     _y += value18 19     this20   }21 22   def +(value: FunctionalObjects): FunctionalObjects = { 23     _x += value.x24     _y += value.y25 26     this27   }28 29 30   override def toString(): String = {31     "("+ _x +", "+ _y +")"32   }33 }34 35 object FunctionalObjects {36   implicit def intToFunctionalObjectsTest(value: Int) = new FunctionalObjects(value)37 38   def main(args: Array[String]) {39     var test = new FunctionalObjects(5)40     test.y = 641     println(test)42     println(test + 4)43     println(4 + test)44   }45 }

隐式类型转换、运算符方法、属性语法,这些都不必多说,大家一看就明白,scala的构造方法得简单的解释一下,类型名称后面跟随的参数列表就是“主要构造函数”的签名,类型定义中出现的可执行语句,都是其方法体。def this 定义的构造方法为“次要构造方法”。

 

Scala:Functional Objects