Scala Trait 示例–Rectangular 对象

2018-09-28 18:18 更新

Trait 示例–Rectangular 对象

``class Point(val x:Int, val y:Int)``
``````class Rectangle(val topLeft:Point, val bottomRight:Point){
def left =topLeft.x
def right =bottomRight.x
def width=right-left
// and many more geometric methods
}``````

``````abstract class Component {
def topLeft :Point
def bottomRight:Point
def left =topLeft.x
def right =bottomRight.x
def width=right-left
// and many more geometric methods
}``````

``````trait Rectangular {
def topLeft:Point
def bottomRight:Point
def left =topLeft.x
def right =bottomRight.x
def width=right-left
// and many more geometric methods
}``````

``````abstract class Component extends Rectangular{
//other methods
}``````

``````class Rectangle(val topLeft:Point, val bottomRight:Point) extends Rectangular{
// other methods
}``````

``````object TestConsole extends App{
val rect=new Rectangle(new Point(1,1),new Point(10,10))
println (rect.left)
println(rect.right)
println(rect.width)
}``````

``````1
10
9``````

App下载