Reputation: 93
My code is as follows:
class HuffmanNode(val chars: String, val occurrences: Int) {
override def toString: String = "{" + chars + "|" + occurrences + "}"
def absoluteValue: Int = occurrences
def getChars: String = chars
def getOccurrences: String = occurrences.toString
}
object HuffmanNode {
def apply(chars: String, occurrences: Int): HuffmanNode = {
new HuffmanNode(chars, occurrences)
}
}
I'm trying to create a list of HuffmanNode
, e.g.:
val PQ: List[HuffmanNode] = List(HuffmanNode("a", 3), HuffmanNode("b", 3))
How do I access the methods inside the HuffmanNode?
I tried doing this:
PQ(0).getChars
But I get an error saying, unable to resolve symbol getChars
.
What could the problem be?
Upvotes: 1
Views: 77
Reputation: 967
As pointed out by @Assaf Mendelson you refer to the singleton object instead of instance of the class.
In order to fix you code you should create instance of the class instead like:
val PQ = List(HuffmanNode("blabla", 2))
val chars = PQ(0).getChars // now compiles
Upvotes: 0
Reputation: 709
If you change code as I suggested in edit, there is no problem to invoke getChars
method:
class HuffmanNode(val chars: String, val occurrences: Int) {
override def toString: String = "{" + chars + "|" + occurrences + "}"
def absoluteValue: Int = occurrences
def getChars: String = chars
def getOccurrences: String = occurrences.toString
}
object HuffmanNode {
def apply(chars: String, occurrences: Int): HuffmanNode = {
new HuffmanNode(chars, occurrences)
}
}
val PQ: List[HuffmanNode] = List(HuffmanNode("a", 3), HuffmanNode("b", 3))
PQ(1).getChars
I got:
PQ: List[HuffmanNode] = List({a|3}, {b|3})
res0: String = b
However I needed (just to test) remove keyword override from absoluteValue
method.
Upvotes: 0
Reputation: 13001
Your code does not compile. If I would hazard a guess I would imagine that you are using a list of the singleton instead of an instance of the class (the singleton does not have a getChars method, only the apply).
Upvotes: 1