Scala 添加方法来扩展某些东西
我在 BinarySearchTree 中创建了 lowerBound 方法。
BinarySearchTree 扩展了 TreeMap[Int, Int]。
所以我在BinarySearchTree中做了lowerBound方法。
但编译器说
treetest.scala:85: error: value lowerNeighbor is not a member of TreeMap[Int,Int] t2.lowerNeighbor(3)
How to made it? :)
class BinarySearchTree(private val root: Node) extends TreeMap[Int, Int] {
def lowerNeighbor(x : Int) : Int = {
var t = root
.........
}
}
var t2: TreeMap[Int, Int] = new BinarySearchTree
t2.lowerNeighbor(3)
I made lowerBound method in my BinarySearchTree.
BinarySearchTree extends TreeMap[Int, Int].
So I made lowerBound method in BinarySearchTree.
but compiler said
treetest.scala:85: error: value lowerNeighbor is not a member of TreeMap[Int,Int] t2.lowerNeighbor(3)
How to made it? :)
class BinarySearchTree(private val root: Node) extends TreeMap[Int, Int] {
def lowerNeighbor(x : Int) : Int = {
var t = root
.........
}
}
var t2: TreeMap[Int, Int] = new BinarySearchTree
t2.lowerNeighbor(3)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您已将
t2
变量声明为静态类型TreeMap[Int, Int]
。因此,对于编译器来说,每次使用t2
时,它都会假设它是TreeMap[Int, Int]
的实例。lowerNeighbor
不是在TreeMap
上定义的方法,而是在BinarySearchTree
上定义的方法。如果您想调用lowerNeighbor
方法,变量的静态类型必须是BinarySearchTree
。** 这会忽略隐式转换,您可能需要阅读一旦您弄清楚静态类型与动态类型问题,就可以继续。
You have declared your
t2
variable to be of the static typeTreeMap[Int, Int]
. Therefore, for the compiler, each time you uset2
, it will assume it is an instance ofTreeMap[Int, Int]
.lowerNeighbor
is not a method defined onTreeMap
s, but onBinarySearchTree
s. The static type of your variable has to beBinarySearchTree
if you want to call thelowerNeighbor
method.** This is ignoring implicit conversions, which you may want to read up on once you've figured out the static type vs. dynamic type issue.