Scala 点类 (Point) 伴生对象构造实例 - 无需 new 直接使用 Point(x, y)
class Point private(val x: Int, val y: Int) { def distance(that: Point): Double = { math.sqrt((that.x - x) * (that.x - x) + (that.y - y) * (that.y - y)) } override def toString: String = s'点(x=$x, y=$y)' }
object Point { def apply(x: Int, y: Int): Point = new Point(x, y) }
object Main extends App { 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)}") }
原文地址: https://www.cveoy.top/t/topic/kvEB 著作权归作者所有。请勿转载和采集!