定义一个 Point 类和一个伴生对象使得我们可以不用 new 而直接用 Point34来构造 Point 类的实例在 Point 类中定义一个 distance 方法用来计算两个点之间的距离例如点34和点310之间的距离为6。运行结果如下:x=3 y=4点34和点310之间的距离=60用Scala写完整代码
class Point private (val x: Double, val y: Double) {
def distance(other: Point): Double = {
math.sqrt(math.pow(x - other.x, 2) + math.pow(y - other.y, 2))
}
override def toString: String = s"x=$x, y=$y"
}
object Point {
def apply(x: Double, y: Double): Point = new Point(x, y)
}
object Main extends App {
val p1 = Point(3, 4)
val p2 = Point(3, 10)
println(p1)
println(s"点${p1}和点${p2}之间的距离=${p1.distance(p2)}")
}
原文地址: https://www.cveoy.top/t/topic/cZH8 著作权归作者所有。请勿转载和采集!