1

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?

3 Answers 3

1

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Right! I was doing what you just said
@Vasu, if the answer helps, you should mark it as Accepted
0

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.

Comments

0

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

1 Comment

Actually the whole point of having an object with an apply is not to use new yourself, you should instead use val PQ = List(HuffmanNode("blabla", 2))

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.