如何访问列表中的对象 - Scala

时间:2018-01-31 10:22:04

标签: scala

我的代码如下:

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

我试图创建一个HuffmanNode列表,例如:

val PQ: List[HuffmanNode] = List(HuffmanNode("a", 3), HuffmanNode("b", 3))

如何访问HuffmanNode中的方法?

我试过这样做:

PQ(0).getChars

但我收到错误提示unable to resolve symbol getChars

问题是什么?

3 个答案:

答案 0 :(得分:1)

您的代码无法编译。如果我冒险猜测我会想象你正在使用单例列表而不是类的实例(单例没有getChars方法,只有apply)。

答案 1 :(得分:0)

正如@Assaf Mendelson指出的那样,你引用的是单例对象而不是类的实例。

为了修复代码,你应该创建类的实例,如:

  val PQ = List(HuffmanNode("blabla", 2))
  val chars = PQ(0).getChars // now compiles

答案 2 :(得分:0)

如果您按照我在编辑中的建议更改代码,则调用getChars方法没有问题:

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

我得到了:

PQ: List[HuffmanNode] = List({a|3}, {b|3})

res0: String = b

但是,我需要(仅测试)从absoluteValue方法中删除关键字覆盖。