class A {
def algorithmImplementation (...) = { ... }
}
object A {
def algorithmImplementation (...) = { ... }
}
在什么情况下应该使用
class
,什么情况下应该使用 object
(例如实现一个算法,如上所示的 Dijkstra 算法)?在做出这样的决定时应考虑哪些标准?
目前,我真的看不出使用
class
的好处。class A {
def algorithmImplementation (...) = { ... }
}
object A {
def algorithmImplementation (...) = { ... }
}
class
,什么情况下应该使用 object
(例如实现一个算法,如上所示的 Dijkstra 算法)?class
的好处。类可以有子类来覆盖实现,对象无法被子类化。类还可以是类型参数化的,而对象不行。
每个容器中只有一个对象实例,或者至少有一个实例。类有多个实例。这意味着类可以使用值进行参数化。
class A(param1 : int, param2 : int) {
def algorithmImplementation(arg : List[String]) = // use arg and params
}
这可以像复用一样使用
val A42_13 = new A(42, 13)
val result1 = A42_13.algorithmImplementation(List("hello", "world"))
val result2 = A42_13.algorithmImplementation(List("goodbye", "cruel", "world"))
val Djikstra[Node, Metric <: Comparable[Metric]](distance : (Node, Node) => Metric) {
def compute(node : Node, nodes : Seq[Node]) : Seq[Metric] = {...}
}
每次计算Djikstra时,您需要为每种不同类型的节点/度量/距离函数创建一个Djikstra实例,并重复使用该实例,而无需每次都传递所有信息。
总之,类更加灵活。在需要灵活性时使用它们。否则,对象就可以了。