代码如下:

class Point private (val x: Int, val y: Int) { 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: Int, y: Int): Point = new Point(x, y) }

// 测试代码 val p1 = Point(3, 4) val p2 = Point(3, 10) println(s"x=${p1.x}, y=${p1.y}") println(s"$p1和$p2之间的距离=${p1.distance(p2)}")

定义一个 Point 类和一个伴生对象使得我们可以不用 new 而直接用 Point34来构造 Point 类的实例在 Point 类中定义一个 distance 方法用来计算两个点之间的距离例如点34和点310之间的距离为6。运行结果如下:x=3 y=4点x=3 y=4和点x=3 y=10之间的距离=6用Scala写输出一模一样的结果

原文地址: https://www.cveoy.top/t/topic/c8d3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录