Scala 添加方法来扩展某些东西

发布于 2024-12-18 02:04:52 字数 555 浏览 0 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

尝蛊 2024-12-25 02:04:52

您已将 t2 变量声明为静态类型 TreeMap[Int, Int]。因此,对于编译器来说,每次使用t2时,它都会假设它是TreeMap[Int, Int]的实例。 lowerNeighbor 不是在 TreeMap 上定义的方法,而是在 BinarySearchTree 上定义的方法。如果您想调用 lowerNeighbor 方法,变量的静态类型必须是 BinarySearchTree。*

* 这会忽略隐式转换,您可能需要阅读一旦您弄清楚静态类型与动态类型问题,就可以继续。

You have declared your t2 variable to be of the static type TreeMap[Int, Int]. Therefore, for the compiler, each time you use t2, it will assume it is an instance of TreeMap[Int, Int]. lowerNeighbor is not a method defined on TreeMaps, but on BinarySearchTrees. The static type of your variable has to be BinarySearchTree if you want to call the lowerNeighbor 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文