先上代码
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 = _y 12 13 def y_=(value: Int) { _y = value } 14 15 def +(value: Int): FunctionalObjects = { 16 _x += value 17 _y += value 18 19 this 20 } 21 22 def +(value: FunctionalObjects): FunctionalObjects = { 23 _x += value.x 24 _y += value.y 25 26 this 27 } 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 = 6 41 println(test) 42 println(test + 4) 43 println(4 + test) 44 } 45 }
隐式类型转换、运算符方法、属性语法,这些都不必多说,大家一看就明白,scala的构造方法得简单的解释一下,类型名称后面跟随的参数列表就是“主要构造函数”的签名,类型定义中出现的可执行语句,都是其方法体。def this 定义的构造方法为“次要构造方法”。
时间: 2024-12-29 13:00:39