我有一个使用Ordering
的二进制搜索树实现:
type
TX1=class
function ThisMethod(whatever:Integer;callOldOne:Boolean=false):integer;virtual;
end;
TX2=class(TX1)
function ThisMethod(whatever:Integer;callOldOne:Boolean=false):integer;override;
end;
function TX1.ThisMethod(whatever:Integer;callOldOne:Boolean=false):integer;
begin
result:=1;
end;
function TX2.ThisMethod(whatever:Integer;callOldOne:Boolean=false):integer;
begin
if callOldOne then result:=inherited ThisMethod(whatever) else Result:=2;
end;
如果我使用new并使用明确的case class Bst[T](rootNode: Node[T]) {
def this(rootValue: T, o: Ordering[T]) = this(Node(rootValue, o))
def +=(value: T) = {
val node: Node[T] = rootNode.withValue(value)
node match {
case it if it == rootNode => this
case _ => new Bst[T](node)
}
}
}
case class Node[T](value: T,
ordering: Ordering[T],
left: Option[Node[T]] = None,
right: Option[Node[T]] = None) {
def withValue(v: T): Node[T] = {
ordering.compare(v, value) match {
case comp if comp < 0 =>
Node(value, ordering, node(left, v), right)
case comp if comp > 0 =>
Node(value, ordering, left, node(right, v))
case _ => this
}
}
private def node(ref: Option[Node[T]], v: T): Option[Node[T]] = {
ref.map(_.withValue(v)) orElse Some(Node(v, ordering))
}
}
:
Ordering
但我想在没有object Tester {
def main(args: Array[String]) {
val bst = new Bst[Int](12, Ordering.Int) += 4 += 115 += 19 += 333
}
}
的情况下对其进行初始化,最好也不要使用明确的new
。但是我希望这个类仍然支持不同的泛型类型。我需要做什么?
答案 0 :(得分:4)
您可以为Bst
定义明确的随播广告对象:
object Bst {
def apply[T](rootValue: T, o: Ordering[T]) = new Bst(rootValue, o)
}
然后您可以使用Bst(1, Ordering.Int)
创建Bst
实例。
scala> Bst(12, Ordering.Int) += 4 += 115
res0: Bst[Int] = Bst(Node(12,scala.math.Ordering$Int$@42c2b246,Some(Node(4,scala.math.Ordering$Int$@42c2b246,None,None)),Some(Node(115,scala.math.Ordering$Int$@42c2b246,None,None))))
如果要创建没有显式Ordering
的对象,可以定义为:
object Bst {
def apply[T: Ordering](rootValue: T) = new Bst(rootValue, implicitly[Ordering[T]])
}
然后:
scala> Bst(1)
res1: Bst[Int] = Bst(Node(1,scala.math.Ordering$Int$@42c2b246,None,None))