Silvester
Silvester

Reputation: 3159

Scala add method in extend something

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)

Upvotes: 0

Views: 127

Answers (1)

Jean-Philippe Pellet
Jean-Philippe Pellet

Reputation: 59994

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.

Upvotes: 2

Related Questions